Compare commits
71
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86965d6d45 | ||
|
|
3cbca35fcb | ||
|
|
664f00e510 | ||
|
|
4554af8056 | ||
|
|
f2b6626f6a | ||
|
|
b1b09a6db4 | ||
|
|
221ce8ca81 | ||
|
|
e40f8639b3 | ||
|
|
eba1a4d094 | ||
|
|
e1d0f6b023 | ||
|
|
6f14437855 | ||
|
|
c46f4a032b | ||
|
|
e95ba4f986 | ||
|
|
381720763c | ||
|
|
a3ab1b6657 | ||
|
|
8ad71c54d2 | ||
|
|
e5cbc6faca | ||
|
|
0d51c673eb | ||
|
|
fdf226535b | ||
|
|
f8561fe0e5 | ||
|
|
8026eceab4 | ||
|
|
8442d0a3d8 | ||
|
|
ef1635e59a | ||
|
|
4410fb3ee0 | ||
|
|
9f63059461 | ||
|
|
ee4911029e | ||
|
|
79f3344568 | ||
|
|
dba6292cd4 | ||
|
|
0689c0a591 | ||
|
|
c255783cec | ||
|
|
d695566a7a | ||
|
|
7e22e12cac | ||
|
|
98df5e9e3b | ||
|
|
750c1ed1d9 | ||
|
|
86f2d0aa07 | ||
|
|
ef2783ecfb | ||
|
|
7e4e208d18 | ||
|
|
ad63db78f3 | ||
|
|
f4a435c71a | ||
|
|
154b8a434c | ||
|
|
3a039e5c50 | ||
|
|
6862dec201 | ||
|
|
6f9aa46943 | ||
|
|
73c0a716b9 | ||
|
|
4170e3bd29 | ||
|
|
dff9e2344e | ||
|
|
e4a3cb7f7b | ||
|
|
37f48defcc | ||
|
|
ccac78a6c9 | ||
|
|
799869c6a4 | ||
|
|
bfccfe7eed | ||
|
|
9a9e5e157e | ||
|
|
2d2ffffa33 | ||
|
|
150a64e100 | ||
|
|
234e642e4d | ||
|
|
40d20cb7d1 | ||
|
|
3bcfc09417 | ||
|
|
33f8f899d6 | ||
|
|
0c10880e4f | ||
|
|
ac9d20b812 | ||
|
|
cf11c8a474 | ||
|
|
64248c09fa | ||
|
|
987c67d4d3 | ||
|
|
3a728c3255 | ||
|
|
9005c12164 | ||
|
|
2d458d9116 | ||
|
|
65fe8f5c6c | ||
|
|
0dc0470c60 | ||
|
|
382c1724a3 | ||
|
|
4587912e5b | ||
|
|
d0eb79bb9b |
No files matched your search
@@ -34,3 +34,6 @@ Thumbs.db
|
|||||||
/scripts/deploy.*.env
|
/scripts/deploy.*.env
|
||||||
!/scripts/deploy.example.env
|
!/scripts/deploy.example.env
|
||||||
storage/app/private/exports/
|
storage/app/private/exports/
|
||||||
|
|
||||||
|
# Obsidian: persönlicher Fensterzustand des Editors
|
||||||
|
docs/Prozessarchitektur/.obsidian/workspace.json
|
||||||
@@ -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.
|
- 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`.
|
- 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`.
|
- 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).
|
- 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).
|
- 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`.
|
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
use App\Models\Guest;
|
use App\Models\Guest;
|
||||||
use App\Models\PortalEmail;
|
use App\Models\PortalEmail;
|
||||||
|
use App\Models\ProcessTestRun;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GDPR storage limitation: anonymises guests whose last stay ended longer ago than the retention period, and
|
* GDPR storage limitation: anonymises guests whose last stay ended longer ago than the retention period, and
|
||||||
@@ -44,6 +45,9 @@ public function handle(): int
|
|||||||
|
|
||||||
private function purgeOperationalData(): void
|
private function purgeOperationalData(): void
|
||||||
{
|
{
|
||||||
|
// Process tester reports (synthetic data only, decision O3).
|
||||||
|
ProcessTestRun::query()->where('created_at', '<', now()->subDays(config('fewo.retention.process_test_run_days')))->delete();
|
||||||
|
|
||||||
PortalEmail::query()
|
PortalEmail::query()
|
||||||
->whereNotNull('excerpt')
|
->whereNotNull('excerpt')
|
||||||
->where('received_at', '<', now()->subDays(config('fewo.retention.portal_email_excerpt_days')))
|
->where('received_at', '<', now()->subDays(config('fewo.retention.portal_email_excerpt_days')))
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ public function handle(Booking|BlockedPeriod $occupation, ?int $guestId, array $
|
|||||||
'tags' => ['nullable', 'array'],
|
'tags' => ['nullable', 'array'],
|
||||||
'tags.*' => ['string', 'max:255'],
|
'tags.*' => ['string', 'max:255'],
|
||||||
])->validate();
|
])->validate();
|
||||||
$guest = new Guest([...$data, 'last_name' => $data['last_name'] ?? '', 'email' => filled($data['email'] ?? null) ? mb_strtolower(trim($data['email'])) : null, 'country' => $data['country'] ?? 'DE']);
|
$guest = new Guest([...$data, 'last_name' => $data['last_name'] ?? '', 'email' => filled($data['email'] ?? null) ? mb_strtolower(trim($data['email'])) : null, 'country' => $data['country'] ?? null]);
|
||||||
$guest->forceFill(['tenant_id' => $record->tenant_id])->save();
|
$guest->forceFill(['tenant_id' => $record->tenant_id])->save();
|
||||||
}
|
}
|
||||||
$record->forceFill(['guest_id' => $guest->id])->save();
|
$record->forceFill(['guest_id' => $guest->id])->save();
|
||||||
|
|||||||
+39
-10
@@ -4,11 +4,16 @@
|
|||||||
|
|
||||||
use App\Availability\AvailabilityChecker;
|
use App\Availability\AvailabilityChecker;
|
||||||
use App\Availability\CalendarClearance;
|
use App\Availability\CalendarClearance;
|
||||||
|
use App\Documents\DocumentComposer;
|
||||||
|
use App\Documents\DocumentFinding;
|
||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
use App\Enums\OfferMode;
|
use App\Enums\DocumentKind;
|
||||||
|
use App\Enums\InquiryAnswer;
|
||||||
|
use App\Enums\ProcessingMode;
|
||||||
use App\Exceptions\ReservationException;
|
use App\Exceptions\ReservationException;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
use App\Pricing\QuoteException;
|
use App\Pricing\QuoteException;
|
||||||
|
use App\Process\CaseRequirements;
|
||||||
use App\Support\Content;
|
use App\Support\Content;
|
||||||
use App\Support\Settings;
|
use App\Support\Settings;
|
||||||
|
|
||||||
@@ -16,9 +21,13 @@
|
|||||||
* Automatic offer processing (property setting "Automatisch"): sends the offer without the landlord when every
|
* Automatic offer processing (property setting "Automatisch"): sends the offer without the landlord when every
|
||||||
* release rule is met, otherwise leaves the request untouched for manual processing and says why.
|
* release rule is met, otherwise leaves the request untouched for manual processing and says why.
|
||||||
*
|
*
|
||||||
|
* A request without a hold (pre-reservation "no") gets the information "unter Vorbehalt" instead of the offer (package 7);
|
||||||
|
* its rules are the same except the reservation.
|
||||||
|
*
|
||||||
* Rules: pre-reservation active (the dates are really blocked), guest e-mail known, dates still free, contract
|
* 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),
|
* 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
|
class AutoOffer
|
||||||
{
|
{
|
||||||
@@ -26,11 +35,12 @@ public function __construct(
|
|||||||
private SendOffer $sendOffer,
|
private SendOffer $sendOffer,
|
||||||
private CalendarClearance $clearance,
|
private CalendarClearance $clearance,
|
||||||
private AvailabilityChecker $availability,
|
private AvailabilityChecker $availability,
|
||||||
|
private SendInformation $sendInformation,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function applies(Booking $booking): bool
|
public function applies(Booking $booking): bool
|
||||||
{
|
{
|
||||||
return $booking->property->offer_mode === OfferMode::Automatic;
|
return $booking->processingMode() === ProcessingMode::Automatic;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -40,15 +50,22 @@ public function blockers(Booking $booking): array
|
|||||||
{
|
{
|
||||||
$property = $booking->property;
|
$property = $booking->property;
|
||||||
$reasons = [];
|
$reasons = [];
|
||||||
|
$information = $booking->process()->inquiryAnswer() === InquiryAnswer::Information;
|
||||||
|
|
||||||
if (! $property->pre_reservation_enabled) {
|
if ($information && ($booking->status !== BookingStatus::Reserved || $booking->information_version > 0)) {
|
||||||
$reasons[] = 'Die Vorreservierung ist für diese Wohnung ausgeschaltet; ohne Sperre im Kalender wird kein Angebot automatisch erteilt.';
|
$reasons[] = 'Die Anfrage ist bereits beantwortet oder nicht mehr offen.';
|
||||||
}
|
}
|
||||||
if ($booking->status !== BookingStatus::Reserved || ! $booking->isHoldActive()) {
|
// A request after its clarification hold (v0.11) only needs free dates, which are checked below.
|
||||||
|
$clarified = $booking->hold_purpose === Booking::HOLD_CLARIFICATION;
|
||||||
|
// Without a reservation at the request (offer without early hold) the offer itself creates the hold; availability is checked below.
|
||||||
|
$holdRequired = $booking->process()->preReservation();
|
||||||
|
if (! $information && ($booking->status !== BookingStatus::Reserved || ($holdRequired && ! $clarified && ! $booking->isHoldActive()))) {
|
||||||
$reasons[] = 'Die Anfrage ist nicht mehr vorgemerkt (Frist abgelaufen oder bereits bearbeitet).';
|
$reasons[] = 'Die Anfrage ist nicht mehr vorgemerkt (Frist abgelaufen oder bereits bearbeitet).';
|
||||||
}
|
}
|
||||||
if (blank($booking->guest?->email)) {
|
if (blank($booking->guest?->email)) {
|
||||||
$reasons[] = 'Die E-Mail-Adresse des Gastes fehlt.';
|
$reasons[] = 'Die E-Mail-Adresse des Gastes fehlt.';
|
||||||
|
} elseif (! $information && ($missing = CaseRequirements::blocker($booking, CaseRequirements::OFFER)) !== null) {
|
||||||
|
$reasons[] = $missing;
|
||||||
}
|
}
|
||||||
if (! $this->availability->isAvailable($property, $booking->arrival, $booking->departure, ignore: $booking)) {
|
if (! $this->availability->isAvailable($property, $booking->arrival, $booking->departure, ignore: $booking)) {
|
||||||
$reasons[] = 'Der Zeitraum ist inzwischen belegt.';
|
$reasons[] = 'Der Zeitraum ist inzwischen belegt.';
|
||||||
@@ -57,7 +74,11 @@ public function blockers(Booking $booking): array
|
|||||||
$reasons[] = 'Mietbedingungen, Stornobedingungen oder Bankverbindung sind noch nicht vom Betreiber freigegeben (leer oder Mustertext).';
|
$reasons[] = 'Mietbedingungen, Stornobedingungen oder Bankverbindung sind noch nicht vom Betreiber freigegeben (leer oder Mustertext).';
|
||||||
}
|
}
|
||||||
|
|
||||||
return [...$reasons, ...$this->clearance->reasons($property, $booking->created_at)];
|
// Status, e-mail and dates are checked above; the composition adds what concerns the document.
|
||||||
|
$reasons = [...$reasons, ...app(DocumentComposer::class)->compose($booking, $information ? DocumentKind::Information : DocumentKind::Offer)->toConfirm(except: [DocumentFinding::HOLD_ZERO])];
|
||||||
|
|
||||||
|
// An information reserves nothing and binds nobody: the calendar is checked again when the guest asks for the booking.
|
||||||
|
return $information ? $reasons : [...$reasons, ...$this->clearance->reasons($property, $booking->created_at)];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -69,7 +90,7 @@ public function handle(Booking $booking): array
|
|||||||
{
|
{
|
||||||
$booking->loadMissing(['property', 'guest']);
|
$booking->loadMissing(['property', 'guest']);
|
||||||
|
|
||||||
if ($booking->property->pre_reservation_enabled) {
|
if ($booking->process()->inquiryAnswer() === InquiryAnswer::Offer) {
|
||||||
$this->clearance->refresh($booking->property);
|
$this->clearance->refresh($booking->property);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,7 +100,11 @@ public function handle(Booking $booking): array
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$this->sendOffer->handle($booking->fresh());
|
if ($booking->process()->inquiryAnswer() === InquiryAnswer::Information) {
|
||||||
|
$this->sendInformation->handle($booking->fresh(), ['expected_version' => 0, 'acknowledged' => true]);
|
||||||
|
} else {
|
||||||
|
$this->sendOffer->handle($booking->fresh(), ['expected_version' => 0]);
|
||||||
|
}
|
||||||
} catch (QuoteException|ReservationException $exception) {
|
} catch (QuoteException|ReservationException $exception) {
|
||||||
// A mail failure keeps the saved offer (SendOffer reports it in the inbox); the landlord can resend the link.
|
// A mail failure keeps the saved offer (SendOffer reports it in the inbox); the landlord can resend the link.
|
||||||
return [$exception->getMessage()];
|
return [$exception->getMessage()];
|
||||||
@@ -88,7 +113,11 @@ public function handle(Booking $booking): array
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function contractTextsReleased(): bool
|
/**
|
||||||
|
* Whether the landlord's own contract terms, cancellation terms and bank account are in place (always true while
|
||||||
|
* mails only go to the test recipient).
|
||||||
|
*/
|
||||||
|
public function contractTextsReleased(): bool
|
||||||
{
|
{
|
||||||
if (! Settings::isLive()) {
|
if (! Settings::isLive()) {
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -5,11 +5,14 @@
|
|||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
use App\Enums\BookingTaskKind;
|
use App\Enums\BookingTaskKind;
|
||||||
use App\Enums\BookingTaskStatus;
|
use App\Enums\BookingTaskStatus;
|
||||||
|
use App\Enums\Responsibility;
|
||||||
use App\Exceptions\ReservationException;
|
use App\Exceptions\ReservationException;
|
||||||
use App\Mail\BookingCancelled;
|
use App\Mail\BookingCancelled;
|
||||||
use App\Mail\CancellationRequested;
|
use App\Mail\CancellationRequested;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
use App\Models\BookingTask;
|
use App\Models\BookingTask;
|
||||||
|
use App\Process\CaseClosure;
|
||||||
|
use App\Process\CaseLog;
|
||||||
use App\Support\CancellationCost;
|
use App\Support\CancellationCost;
|
||||||
use App\Support\Money;
|
use App\Support\Money;
|
||||||
use App\Support\Settings;
|
use App\Support\Settings;
|
||||||
@@ -19,35 +22,57 @@
|
|||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The landlord cancels a binding booking. The dates are free again; the guest and the landlord are informed by mail
|
* The one way to cancel a binding booking (package 5). Own bookings: the dates are free again; the guest and the
|
||||||
* (the guest mail can be switched off, e.g. when the guest cancelled by phone and was told already) and a task for
|
* landlord are informed by e-mail – the guest's e-mail can be switched off, e.g. when the guest cancelled by phone –, the
|
||||||
* the cancellation costs is created. Open cancellation requests of the guest are completed.
|
* 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
|
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)
|
* @return bool whether the guest has been informed (true as well when no mail was wanted; false when it failed)
|
||||||
*
|
*
|
||||||
* @throws ReservationException
|
* @throws ReservationException
|
||||||
*/
|
*/
|
||||||
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung'): 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)) {
|
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.');
|
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): void {
|
DB::transaction(function () use ($booking, $costsTask, $by, $initiatedBy, $reason): void {
|
||||||
$booking->lockForTransition();
|
$booking->lockForTransition();
|
||||||
|
|
||||||
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
|
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
|
||||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
|
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
|
||||||
}
|
}
|
||||||
|
|
||||||
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
|
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now(), 'portal_cancellation_requested_at' => null]);
|
||||||
app(RecordCancellation::class)->handle($booking, 'landlord');
|
app(RecordCancellation::class)->handle($booking, $initiatedBy)->update(['reason' => $reason, 'recorded_by' => $by]);
|
||||||
|
|
||||||
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()]);
|
->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]);
|
||||||
|
// The stay will not take place: its preparation is no longer needed (package 9); issues and follow-ups stay.
|
||||||
|
BookingTask::query()->where('booking_id', $booking->id)
|
||||||
|
->whereIn('kind', [BookingTaskKind::ArrivalDetails, BookingTaskKind::Service, BookingTaskKind::DepositReminder, BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder])
|
||||||
|
->where('status', BookingTaskStatus::Open)
|
||||||
|
->update(['status' => BookingTaskStatus::Dismissed, 'note' => 'Storniert – entfällt.', 'completed_by' => $by, 'completed_at' => now()]);
|
||||||
|
|
||||||
|
$this->refundTask($booking);
|
||||||
|
|
||||||
if ($costsTask) {
|
if ($costsTask) {
|
||||||
$cost = CancellationCost::calculate($booking);
|
$cost = CancellationCost::calculate($booking);
|
||||||
@@ -60,10 +85,66 @@ public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTa
|
|||||||
});
|
});
|
||||||
|
|
||||||
$booking->loadMissing(['guest', 'property']);
|
$booking->loadMissing(['guest', 'property']);
|
||||||
|
// A cancellation without anything to settle is closed commercially at once; costs or a refund keep it open.
|
||||||
|
CaseClosure::refresh($booking->fresh());
|
||||||
|
|
||||||
return $this->notify($booking, $notifyGuest);
|
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
|
private function notify(Booking $booking, bool $notifyGuest): bool
|
||||||
{
|
{
|
||||||
$informed = true;
|
$informed = true;
|
||||||
|
|||||||
@@ -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']];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Enums\BookingTaskStatus;
|
||||||
|
use App\Enums\Responsibility;
|
||||||
|
use App\Exceptions\ReservationException;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingTask;
|
||||||
|
use App\Pricing\CaseMoney;
|
||||||
|
use App\Process\CaseClosure;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Support\Money;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Package 9, P05 (gate B4 as decided by the operator): closes the stay after the departure – automatically once no task
|
||||||
|
* of the stay is open any more, or by the landlord, who marks the remaining stay tasks as done or handed over. Open
|
||||||
|
* money does not hold the stay up: it becomes a follow-up on the same case (claim against the guest, payout of the
|
||||||
|
* portal) and keeps the commercial closing open until it is clear.
|
||||||
|
*/
|
||||||
|
class CloseStay
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Daily: closes every stay whose departure has passed and nothing of the stay is open any more.
|
||||||
|
*
|
||||||
|
* @return int the number of stays closed now
|
||||||
|
*/
|
||||||
|
public function due(): int
|
||||||
|
{
|
||||||
|
$closed = 0;
|
||||||
|
$stays = Booking::query()
|
||||||
|
->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid])
|
||||||
|
->whereDate('departure', '<', CarbonImmutable::today())
|
||||||
|
->with(['guest', 'property', 'payments', 'importChannel', 'originChannel'])
|
||||||
|
->get();
|
||||||
|
|
||||||
|
foreach ($stays as $booking) {
|
||||||
|
// After the departure the arrival details are of no use any more.
|
||||||
|
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)->get() as $task) {
|
||||||
|
$task->update(['status' => BookingTaskStatus::Dismissed, 'note' => 'Nach der Abreise nicht mehr nötig.', 'completed_by' => CaseLog::SYSTEM, 'completed_at' => now()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (CaseClosure::stayBlockers($booking)->isNotEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
CaseLog::context(fn () => $this->close($booking), actor: CaseLog::SYSTEM.' (automatisch)');
|
||||||
|
$closed++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cases closed before package 9 (or whose money became clear without a payment) get their commercial closing too.
|
||||||
|
$unsettled = Booking::query()->whereIn('status', [BookingStatus::Completed, BookingStatus::Cancelled])->whereNull('settled_at')
|
||||||
|
->whereDate('departure', '>', CarbonImmutable::today()->subYear())->with(['payments', 'importChannel', 'originChannel'])->get();
|
||||||
|
foreach ($unsettled as $booking) {
|
||||||
|
CaseLog::context(fn () => CaseClosure::refresh($booking), actor: CaseLog::SYSTEM.' (automatisch)');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $closed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The landlord closes the stay; open tasks of the stay are marked as done or handed over with the note.
|
||||||
|
*
|
||||||
|
* @throws ReservationException
|
||||||
|
*/
|
||||||
|
public function byHand(Booking $booking, string $by, ?string $note = null): void
|
||||||
|
{
|
||||||
|
if (! in_array($booking->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true)) {
|
||||||
|
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgeschlossen');
|
||||||
|
}
|
||||||
|
if ($booking->departure->isAfter(CarbonImmutable::today())) {
|
||||||
|
throw new ReservationException('Der Aufenthalt endet erst am '.$booking->departure->format('d.m.Y').'.');
|
||||||
|
}
|
||||||
|
|
||||||
|
CaseLog::context(function () use ($booking, $by, $note): void {
|
||||||
|
foreach (CaseClosure::stayBlockers($booking) as $task) {
|
||||||
|
$task->complete($by, filled($note) ? $note : 'Mit dem Abschluss des Aufenthalts erledigt bzw. übergeben.');
|
||||||
|
}
|
||||||
|
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)
|
||||||
|
->update(['status' => BookingTaskStatus::Dismissed, 'completed_by' => $by, 'completed_at' => now()]);
|
||||||
|
$this->close($booking);
|
||||||
|
}, actor: $by, reason: $note);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function close(Booking $booking): void
|
||||||
|
{
|
||||||
|
DB::transaction(function () use ($booking): void {
|
||||||
|
$booking->lockForTransition();
|
||||||
|
if (! in_array($booking->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$booking->update(['status' => BookingStatus::Completed, 'completed_at' => now()]);
|
||||||
|
$this->followUps($booking);
|
||||||
|
});
|
||||||
|
|
||||||
|
CaseClosure::refresh($booking->fresh());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open money becomes a follow-up of the closed stay, so it stays visible and assigned.
|
||||||
|
*/
|
||||||
|
private function followUps(Booking $booking): void
|
||||||
|
{
|
||||||
|
$booking->unsetRelation('payments');
|
||||||
|
$money = CaseMoney::of($booking);
|
||||||
|
|
||||||
|
if ($money->collector() === Responsibility::Landlord && $money->openForUs() > 0) {
|
||||||
|
$chasing = BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get()->contains(fn (BookingTask $task): bool => $task->kind->isPayment());
|
||||||
|
if (! $chasing) {
|
||||||
|
BookingTask::openOnce($booking, BookingTaskKind::OpenClaim, '', ['due_on' => today(), 'note' => 'Noch offen vom Gast: '.Money::format($money->openForUs()).'.']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($money->collector() === Responsibility::Portal) {
|
||||||
|
$payout = $money->payout();
|
||||||
|
if ($payout['received'] === 0 || ($payout['outstanding'] ?? 0) > 0) {
|
||||||
|
$portal = $booking->processChannel()?->name ?? 'des Portals';
|
||||||
|
BookingTask::openOnce($booking, BookingTaskKind::PayoutCheck, '', [
|
||||||
|
'due_on' => $booking->departure->addDays(14),
|
||||||
|
'responsible' => $booking->processChannel()?->name,
|
||||||
|
'note' => match (true) {
|
||||||
|
$payout['values'] !== [] => 'Angekündigt: '.implode(' bzw. ', array_map(fn (int $value): string => Money::format($value), $payout['values'])).'; erhalten: '.Money::format($payout['received']).'.',
|
||||||
|
default => 'Auszahlung von '.$portal.' noch nicht erfasst.',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Enums\IntakeKind;
|
||||||
|
use App\Enums\ProcessSetting;
|
||||||
|
use App\Models\Channel;
|
||||||
|
use App\Process\ChannelCapabilities;
|
||||||
|
use App\Process\ChannelProcessConfiguration;
|
||||||
|
use App\Process\ProcessCatalogue;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves the process of a channel for one intake kind (Kanal › Ablauf, docs/Prozessarchitektur/Architektur/03 and V2.1/02):
|
||||||
|
* the confirmed capabilities of the portal, the chosen model and variant, the step switches and the step settings – in
|
||||||
|
* channels.settings and channels.process_overrides[intake], next to the existing settings, so their inheritance stays
|
||||||
|
* as it is. Refuses everything the configuration does not admit (mandatory steps off, responsibilities the model does not
|
||||||
|
* allow, a model the capabilities do not fit, tester-only variants). Stored settings that the chosen model overrides are
|
||||||
|
* removed only after the landlord confirmed that, and the change is kept in the channel's history. Changes apply to new
|
||||||
|
* cases only (decision E3): running cases keep their frozen plan.
|
||||||
|
*/
|
||||||
|
class ConfigureChannelProcess
|
||||||
|
{
|
||||||
|
public const HISTORY_LIMIT = 20;
|
||||||
|
|
||||||
|
public function __construct(private ChannelProcessConfiguration $configuration, private ChannelCapabilities $capabilities, private ProcessCatalogue $catalogue) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{model: string, variant?: string, steps?: array<string, array{on?: bool}>, settings?: array<string, mixed>, templates?: array<string, string>, capabilities?: array<string, bool|string|null>} $draft
|
||||||
|
* @param bool $acknowledgeConflicts the landlord confirmed that stored settings the model overrides are removed
|
||||||
|
*
|
||||||
|
* @throws ValidationException
|
||||||
|
*/
|
||||||
|
public function handle(Channel $channel, IntakeKind $intake, array $draft, ?string $by = null, bool $acknowledgeConflicts = false): Channel
|
||||||
|
{
|
||||||
|
$problems = $this->configuration->problems($channel, $intake, $draft);
|
||||||
|
if ($problems !== []) {
|
||||||
|
throw ValidationException::withMessages(['process' => $problems]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$conflicts = $this->configuration->conflicts($channel, $intake, (string) $draft['model'], (array) ($draft['templates'] ?? []));
|
||||||
|
if ($conflicts !== [] && ! $acknowledgeConflicts) {
|
||||||
|
throw ValidationException::withMessages(['process' => [
|
||||||
|
'Bisherige Einstellungen widersprechen dem gewählten Modell und würden still überstimmt. Bitte ausdrücklich bestätigen, dass sie entfernt werden:',
|
||||||
|
...array_column($conflicts, 'text'),
|
||||||
|
]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($channel, $intake, $draft, $by, $conflicts): Channel {
|
||||||
|
$channel = Channel::query()->lockForUpdate()->findOrFail($channel->id);
|
||||||
|
$by ??= auth()->user()?->name;
|
||||||
|
$overrides = (array) ($channel->process_overrides ?? []);
|
||||||
|
$current = (array) ($overrides[$intake->value] ?? []);
|
||||||
|
$removed = array_map(fn (array $conflict): string => $conflict['setting']->value, $conflicts);
|
||||||
|
|
||||||
|
$settings = [];
|
||||||
|
foreach (ProcessSetting::cases() as $setting) {
|
||||||
|
if (in_array($setting->value, $removed, true)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$value = array_key_exists($setting->value, (array) ($draft['settings'] ?? [])) ? $setting->normalize($draft['settings'][$setting->value]) : $setting->normalize($current[$setting->value] ?? null);
|
||||||
|
if ($value !== null && in_array($intake, $setting->channelIntakes(), true)) {
|
||||||
|
$settings[$setting->value] = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$steps = [];
|
||||||
|
foreach ((array) ($draft['steps'] ?? []) as $module => $step) {
|
||||||
|
if (array_key_exists('on', $step) && $step['on'] === false) {
|
||||||
|
$steps[$module] = ['on' => false];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A model with slots always stores its explicit template choice (keys; the version is frozen with each new case).
|
||||||
|
$model = $this->catalogue->model((string) $draft['model']);
|
||||||
|
$templates = array_map(fn (string $reference): string => explode('@', $reference)[0], $this->configuration->templatesOf($model, $draft));
|
||||||
|
if ($model->slots() === []) {
|
||||||
|
$templates = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$overrides[$intake->value] = [
|
||||||
|
...$settings,
|
||||||
|
'model' => $draft['model'],
|
||||||
|
'variant' => $draft['variant'] ?? 'standard',
|
||||||
|
'steps' => $steps,
|
||||||
|
'templates' => $templates,
|
||||||
|
'configured_at' => now()->toIso8601String(),
|
||||||
|
'configured_by' => $by,
|
||||||
|
];
|
||||||
|
|
||||||
|
$channelSettings = (array) ($channel->settings ?? []);
|
||||||
|
$changes = [];
|
||||||
|
if (! $channel->isWebsite() && filled($draft['capabilities'] ?? null)) {
|
||||||
|
$confirmed = $this->capabilities->confirm($channel, (array) $draft['capabilities'], $by);
|
||||||
|
$channelSettings['capabilities'] = $confirmed['capabilities'];
|
||||||
|
$changes = $confirmed['changes'];
|
||||||
|
}
|
||||||
|
$channelSettings['process_history'] = array_slice([...(array) ($channelSettings['process_history'] ?? []), [
|
||||||
|
'at' => now()->toIso8601String(), 'by' => $by, 'intake' => $intake->value, 'model' => $draft['model'], 'variant' => $draft['variant'] ?? 'standard', 'templates' => $templates,
|
||||||
|
'capabilities' => $changes, 'removed_settings' => array_map(fn (array $conflict): string => $conflict['text'], $conflicts),
|
||||||
|
]], -self::HISTORY_LIMIT);
|
||||||
|
|
||||||
|
$channel->update(['process_overrides' => $overrides, 'settings' => $channelSettings]);
|
||||||
|
|
||||||
|
return $channel;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,11 +6,15 @@
|
|||||||
use App\Documents\OfferTerms;
|
use App\Documents\OfferTerms;
|
||||||
use App\Documents\RentalContract;
|
use App\Documents\RentalContract;
|
||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\DocumentKind;
|
||||||
use App\Enums\InboxMessageKind;
|
use App\Enums\InboxMessageKind;
|
||||||
use App\Exceptions\ReservationException;
|
use App\Exceptions\ReservationException;
|
||||||
use App\Filament\Resources\Bookings\BookingResource;
|
use App\Filament\Resources\Bookings\BookingResource;
|
||||||
use App\Mail\BookingConfirmed;
|
use App\Mail\BookingConfirmed;
|
||||||
|
use App\Mail\BookingDocumentation;
|
||||||
|
use App\Mail\StayConfirmed;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
|
use App\Process\CaseLog;
|
||||||
use App\Support\Inbox;
|
use App\Support\Inbox;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
@@ -84,25 +88,39 @@ public function bind(Booking $booking): void
|
|||||||
*
|
*
|
||||||
* @return bool whether the guest has the confirmation (true when no mail was requested)
|
* @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']);
|
$booking->loadMissing(['guest', 'property']);
|
||||||
|
$kind ??= DocumentKind::forCase($booking) ?? DocumentKind::Confirmation;
|
||||||
|
|
||||||
try {
|
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) {
|
if (! $notifyGuest) {
|
||||||
return true;
|
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) {
|
||||||
$booking->forceFill(['confirmation_sent_at' => now(), 'confirmation_failed_at' => null])->saveQuietly();
|
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;
|
return true;
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
// Only class and booking id are logged: mail errors can contain the recipient's address.
|
// Only class and booking id are logged: mail errors can contain the recipient's address.
|
||||||
Log::warning('Buchungsbestätigung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
Log::warning('Buchungsbestätigung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||||
$booking->forceFill(['confirmation_failed_at' => now()])->saveQuietly();
|
$booking->forceFill(['confirmation_failed_at' => now()])->save();
|
||||||
$this->inbox->post(
|
$this->inbox->post(
|
||||||
InboxMessageKind::ConfirmationFailed,
|
InboxMessageKind::ConfirmationFailed,
|
||||||
'booking-'.$booking->id,
|
'booking-'.$booking->id,
|
||||||
|
|||||||
@@ -0,0 +1,234 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Enums\BookingTaskStatus;
|
||||||
|
use App\Enums\FactSource;
|
||||||
|
use App\Events\CaseFactsContributed;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingTask;
|
||||||
|
use App\Models\CaseFact;
|
||||||
|
use App\Models\Guest;
|
||||||
|
use App\Process\CaseAutomation;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Process\CaseRequirements;
|
||||||
|
use App\Process\FactContribution;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The common fact intake of v0.11 (S5, CH-03, E-038). Every source – website form, the guest's link, an e-mail,
|
||||||
|
* a portal mail, the extraction, the landlord – hands its details for a case to this one place:
|
||||||
|
*
|
||||||
|
* - a missing value is taken over, an equal one confirmed;
|
||||||
|
* - a different contact or address value from the guest's side is never written over the stored one: it becomes a
|
||||||
|
* conflict for the landlord (the guest record may belong to other cases too);
|
||||||
|
* - the landlord's own entry is authoritative and replaces the value, the previous one stays in the evidence;
|
||||||
|
* - dates and the number of guests are stay details: a differing value (and in a binding case also a missing one from
|
||||||
|
* the guest's side) is only a change request for the landlord – nothing about the booking changes here;
|
||||||
|
* - invalid values are rejected.
|
||||||
|
*
|
||||||
|
* Every detail is recorded with source and outcome. The same contribution again is harmless (idempotent). Afterwards
|
||||||
|
* the existing process is asked once to carry on (S6); this intake decides nothing about offers or bookings.
|
||||||
|
*/
|
||||||
|
class ContributeCaseFacts
|
||||||
|
{
|
||||||
|
/** Stay details: never changed through the intake once known (P02/P03: change requests). */
|
||||||
|
public const STAY_FIELDS = ['booking.guests', 'booking.arrival', 'booking.departure'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $facts field key ({@see CaseRequirements::FIELDS} or OPTIONAL_FIELDS) => value
|
||||||
|
* @param array{reference?: string, inbound_message_id?: int, evidence?: array<string, string>, confidence?: array<string, float>, actor?: string, advance?: bool} $options
|
||||||
|
*/
|
||||||
|
public function handle(Booking $booking, array $facts, FactSource $source, array $options = []): FactContribution
|
||||||
|
{
|
||||||
|
$known = [...CaseRequirements::FIELDS, ...CaseRequirements::OPTIONAL_FIELDS];
|
||||||
|
$facts = array_filter(array_map(fn (mixed $value): mixed => is_string($value) ? trim($value) : $value, array_intersect_key($facts, $known)), fn (mixed $value): bool => $value !== null && $value !== '');
|
||||||
|
if (isset($facts['guest.email'])) {
|
||||||
|
$facts['guest.email'] = mb_strtolower((string) $facts['guest.email']);
|
||||||
|
}
|
||||||
|
if ($facts === []) {
|
||||||
|
return new FactContribution;
|
||||||
|
}
|
||||||
|
|
||||||
|
$actor = $options['actor'] ?? ($source === FactSource::Landlord ? (auth()->user()?->name ?? 'Vermieter') : CaseLog::GUEST);
|
||||||
|
$reference = (string) ($options['reference'] ?? $options['inbound_message_id'] ?? '');
|
||||||
|
|
||||||
|
$contribution = DB::transaction(function () use ($booking, $facts, $source, $options, $actor, $reference): FactContribution {
|
||||||
|
$booking->lockForTransition();
|
||||||
|
$booking->load('guest');
|
||||||
|
|
||||||
|
$recorded = [];
|
||||||
|
$guestChanges = [];
|
||||||
|
$bookingChanges = [];
|
||||||
|
foreach ($facts as $field => $value) {
|
||||||
|
$value = is_scalar($value) ? (string) $value : json_encode($value);
|
||||||
|
$fingerprint = hash('sha256', implode('|', [$booking->id, $source->value, $reference, $field, mb_strtolower($value)]));
|
||||||
|
if (CaseFact::query()->withoutGlobalScopes()->where('booking_id', $booking->id)->where('fingerprint', $fingerprint)->exists()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$current = CaseRequirements::value($booking, $field);
|
||||||
|
$outcome = $this->outcome($booking, $field, $value, $current, $source);
|
||||||
|
if ($outcome === CaseFact::APPLIED) {
|
||||||
|
[$scope, $attribute] = explode('.', $field, 2);
|
||||||
|
if ($scope === 'guest') {
|
||||||
|
$guestChanges[$attribute] = $value;
|
||||||
|
} else {
|
||||||
|
$bookingChanges[$attribute] = $field === 'booking.guests' ? (int) $value : $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$recorded[] = new CaseFact([
|
||||||
|
'booking_id' => $booking->id,
|
||||||
|
'field' => $field,
|
||||||
|
'value' => $value,
|
||||||
|
'previous_value' => filled($current) ? (string) $current : null,
|
||||||
|
'source' => $source,
|
||||||
|
'inbound_message_id' => $options['inbound_message_id'] ?? null,
|
||||||
|
'evidence' => $options['evidence'][$field] ?? null,
|
||||||
|
'confidence' => $options['confidence'][$field] ?? null,
|
||||||
|
'outcome' => $outcome,
|
||||||
|
'fingerprint' => $fingerprint,
|
||||||
|
'actor' => $actor,
|
||||||
|
'created_at' => now(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->applyGuest($booking, $guestChanges, $recorded, $source);
|
||||||
|
if ($bookingChanges !== []) {
|
||||||
|
$booking->update($bookingChanges);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($recorded as $fact) {
|
||||||
|
$fact->tenant_id = $booking->tenant_id;
|
||||||
|
$fact->save();
|
||||||
|
}
|
||||||
|
|
||||||
|
$contribution = new FactContribution($recorded);
|
||||||
|
if (! $contribution->isEmpty()) {
|
||||||
|
$this->openTasks($booking, $contribution, $source);
|
||||||
|
CaseLog::record($booking, 'facts', 'Angaben von '.$source->getLabel().': '.$contribution->summary(), data: ['fields' => array_map(fn (CaseFact $fact): array => ['field' => $fact->field, 'outcome' => $fact->outcome], $recorded)], actor: $actor);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $contribution;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (! $contribution->isEmpty()) {
|
||||||
|
$booking->refresh()->load('guest');
|
||||||
|
event(new CaseFactsContributed($booking, $contribution, $source));
|
||||||
|
|
||||||
|
if ($contribution->anyApplied() && ($options['advance'] ?? true)) {
|
||||||
|
app(CaseAutomation::class)->advance($booking);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $contribution;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase of the case for the rules (CH §1.4): binding (P3) or not.
|
||||||
|
*/
|
||||||
|
public static function isBinding(Booking $booking): bool
|
||||||
|
{
|
||||||
|
return in_array($booking->status, BookingStatus::occupying(), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function outcome(Booking $booking, string $field, string $value, mixed $current, FactSource $source): string
|
||||||
|
{
|
||||||
|
if (! CaseRequirements::isValid($field, $value)) {
|
||||||
|
return CaseFact::REJECTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
$known = CaseRequirements::isValid($field, $current);
|
||||||
|
if ($known && $this->same($field, $value, $current)) {
|
||||||
|
return CaseFact::CONFIRMED;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_array($field, self::STAY_FIELDS, true)) {
|
||||||
|
// A stay detail never changes through the intake. Only an unknown number of guests may be completed – by the
|
||||||
|
// landlord or the portal's own message, or on a request that binds nobody yet.
|
||||||
|
$completes = ! $known && ($source->isAuthoritative() || $source === FactSource::PortalMail || ! self::isBinding($booking));
|
||||||
|
|
||||||
|
return $completes ? CaseFact::APPLIED : CaseFact::CHANGE_REQUEST;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $known || $source->isAuthoritative()) {
|
||||||
|
return CaseFact::APPLIED;
|
||||||
|
}
|
||||||
|
|
||||||
|
return CaseFact::CONFLICT;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function same(string $field, string $value, mixed $current): bool
|
||||||
|
{
|
||||||
|
if ($field === 'booking.guests') {
|
||||||
|
return (int) $value === (int) $current;
|
||||||
|
}
|
||||||
|
|
||||||
|
return mb_strtolower(preg_replace('/\s+/', ' ', $value)) === mb_strtolower(preg_replace('/\s+/', ' ', trim((string) $current)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes the taken-over guest details. A case without a guest gets a new guest record once a name is known; a
|
||||||
|
* known e-mail address never joins another person's record silently (the landlord assigns it).
|
||||||
|
*
|
||||||
|
* @param array<string, string> $changes
|
||||||
|
* @param list<CaseFact> $recorded
|
||||||
|
*/
|
||||||
|
private function applyGuest(Booking $booking, array $changes, array $recorded, FactSource $source): void
|
||||||
|
{
|
||||||
|
if ($changes === []) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($booking->guest !== null) {
|
||||||
|
$booking->guest->update($changes);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$email = $changes['email'] ?? '';
|
||||||
|
// The landlord knows whom he enters; any other source must not attach the case to somebody else's record.
|
||||||
|
$taken = ! $source->isAuthoritative() && $email !== '' && Guest::query()->where('email', $email)->exists();
|
||||||
|
if (blank($changes['first_name'] ?? null) || blank($changes['last_name'] ?? null) || $taken) {
|
||||||
|
foreach ($recorded as $fact) {
|
||||||
|
if ($fact->outcome === CaseFact::APPLIED && str_starts_with($fact->field, 'guest.')) {
|
||||||
|
$fact->outcome = CaseFact::CONFLICT;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$guest = Guest::query()->create([...$changes, 'email' => $email, 'tenant_id' => $booking->tenant_id]);
|
||||||
|
$booking->update(['guest_id' => $guest->id]);
|
||||||
|
$booking->setRelation('guest', $guest);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function openTasks(Booking $booking, FactContribution $contribution, FactSource $source): void
|
||||||
|
{
|
||||||
|
if ($source->isAuthoritative()) {
|
||||||
|
// The landlord's entry settles what was put to him for these details.
|
||||||
|
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::FactConflict)->where('status', BookingTaskStatus::Open)
|
||||||
|
->whereIn('subject', array_map(fn (CaseFact $fact): string => $fact->field, $contribution->facts))
|
||||||
|
->get()->each(fn (BookingTask $task): bool => $task->forceFill(['status' => BookingTaskStatus::Done, 'completed_at' => now(), 'completed_by' => auth()->user()?->name, 'note' => trim($task->note.' · von Ihnen entschieden')])->save());
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($contribution->facts as $fact) {
|
||||||
|
if ($fact->outcome === CaseFact::CONFLICT) {
|
||||||
|
BookingTask::openOnce($booking, BookingTaskKind::FactConflict, $fact->field, [
|
||||||
|
'due_on' => today(),
|
||||||
|
'note' => CaseRequirements::label($fact->field).' laut '.$source->getLabel().': „'.$fact->value.'“'.($fact->previous_value ? ' (bisher „'.$fact->previous_value.'“)' : ' (noch nicht eingetragen – Zuordnung prüfen)'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
if ($fact->outcome === CaseFact::CHANGE_REQUEST) {
|
||||||
|
BookingTask::openOnce($booking, BookingTaskKind::ChangeRequest, $fact->field.':'.substr($fact->fingerprint, 0, 12), [
|
||||||
|
'due_on' => today(),
|
||||||
|
'note' => 'Gewünscht laut '.$source->getLabel().': '.CaseRequirements::label($fact->field).' „'.$fact->value.'“'.($fact->previous_value ? ' (gebucht: „'.$fact->previous_value.'“)' : '').'. Nichts wurde geändert – bitte über „Buchung ändern“ bzw. ein neues Angebot entscheiden.',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,12 +14,13 @@ class CopySeasonsToNextYear
|
|||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @param int|null $alignToWeekday ISO weekday (1 = Monday … 7 = Sunday) or null for the same calendar dates
|
* @param int|null $alignToWeekday ISO weekday (1 = Monday … 7 = Sunday) or null for the same calendar dates
|
||||||
* @return array{created: int, skipped: int}
|
* @return array{created: int, skipped: int, trimmed: int}
|
||||||
*/
|
*/
|
||||||
public function handle(Property $property, int $year, ?int $alignToWeekday = null): array
|
public function handle(Property $property, int $year, ?int $alignToWeekday = null): array
|
||||||
{
|
{
|
||||||
$created = 0;
|
$created = 0;
|
||||||
$skipped = 0;
|
$skipped = 0;
|
||||||
|
$trimmed = 0;
|
||||||
|
|
||||||
$seasons = $property->seasons()->whereYear('starts_on', $year)->orderBy('starts_on')->get();
|
$seasons = $property->seasons()->whereYear('starts_on', $year)->orderBy('starts_on')->get();
|
||||||
|
|
||||||
@@ -38,7 +39,8 @@ public function handle(Property $property, int $year, ?int $alignToWeekday = nul
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($property->seasons()->overlapping($startsOn, $endsOn)->exists()) {
|
[$startsOn, $endsOn, $wasTrimmed] = $this->fitBetweenExisting($property, $startsOn, $endsOn);
|
||||||
|
if ($startsOn === null || $endsOn === null) {
|
||||||
$skipped++;
|
$skipped++;
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
@@ -50,9 +52,38 @@ public function handle(Property $property, int $year, ?int $alignToWeekday = nul
|
|||||||
'ends_on' => $endsOn,
|
'ends_on' => $endsOn,
|
||||||
]);
|
]);
|
||||||
$created++;
|
$created++;
|
||||||
|
$trimmed += $wasTrimmed ? 1 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return ['created' => $created, 'skipped' => $skipped];
|
return ['created' => $created, 'skipped' => $skipped, 'trimmed' => $trimmed];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Existing seasons win. One that only reaches over the start or the end of the copy shortens the copy there (e.g.
|
||||||
|
* a season over the turn of the year that ends a day after the moved start), so no nights stay without a price;
|
||||||
|
* the copy is left out only when an existing season lies within it or covers it completely.
|
||||||
|
*
|
||||||
|
* @return array{0: ?CarbonImmutable, 1: ?CarbonImmutable, 2: bool}
|
||||||
|
*/
|
||||||
|
private function fitBetweenExisting(Property $property, CarbonImmutable $startsOn, CarbonImmutable $endsOn): array
|
||||||
|
{
|
||||||
|
$originalStart = $startsOn;
|
||||||
|
$originalEnd = $endsOn;
|
||||||
|
|
||||||
|
foreach ($property->seasons()->overlapping($startsOn, $endsOn)->get() as $existing) {
|
||||||
|
if ($existing->starts_on->lessThanOrEqualTo($startsOn) && $existing->ends_on->greaterThan($startsOn)) {
|
||||||
|
$startsOn = $existing->ends_on;
|
||||||
|
}
|
||||||
|
if ($existing->ends_on->greaterThanOrEqualTo($endsOn) && $existing->starts_on->lessThan($endsOn)) {
|
||||||
|
$endsOn = $existing->starts_on;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($endsOn->lessThanOrEqualTo($startsOn) || $property->seasons()->overlapping($startsOn, $endsOn)->exists()) {
|
||||||
|
return [null, null, false];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$startsOn, $endsOn, ! $startsOn->equalTo($originalStart) || ! $endsOn->equalTo($originalEnd)];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -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 ?? '']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,15 +4,22 @@
|
|||||||
|
|
||||||
use App\Availability\AvailabilityChecker;
|
use App\Availability\AvailabilityChecker;
|
||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\FactSource;
|
||||||
|
use App\Enums\IntakeKind;
|
||||||
|
use App\Enums\ProcessingMode;
|
||||||
use App\Exceptions\ReservationException;
|
use App\Exceptions\ReservationException;
|
||||||
use App\Mail\NewReservation;
|
use App\Mail\NewReservation;
|
||||||
use App\Mail\ReservationReceived;
|
use App\Mail\ReservationReceived;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
|
use App\Models\Channel;
|
||||||
use App\Models\Guest;
|
use App\Models\Guest;
|
||||||
use App\Models\Property;
|
use App\Models\Property;
|
||||||
use App\Pricing\PriceCalculator;
|
use App\Pricing\PriceCalculator;
|
||||||
use App\Pricing\QuoteException;
|
use App\Pricing\QuoteException;
|
||||||
use App\Pricing\StayRequest;
|
use App\Pricing\StayRequest;
|
||||||
|
use App\Process\ProcessRunner;
|
||||||
|
use App\Process\ProcessSettings;
|
||||||
|
use App\Process\RequestHold;
|
||||||
use App\Support\Settings;
|
use App\Support\Settings;
|
||||||
use App\Tenancy\TenantContext;
|
use App\Tenancy\TenantContext;
|
||||||
use App\Tenancy\TenantContextMissing;
|
use App\Tenancy\TenantContextMissing;
|
||||||
@@ -23,7 +30,7 @@
|
|||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Turns a guest request into a reservation that holds the dates for the property's hold time,
|
* Turns a guest request into a case (intake "request") that holds the dates for the hold time of the process settings,
|
||||||
* and sends the quote to the guest and a notification to the landlord.
|
* and sends the quote to the guest and a notification to the landlord.
|
||||||
*/
|
*/
|
||||||
class CreateReservation
|
class CreateReservation
|
||||||
@@ -40,7 +47,7 @@ public function __construct(
|
|||||||
* @throws QuoteException
|
* @throws QuoteException
|
||||||
* @throws ReservationException
|
* @throws ReservationException
|
||||||
*/
|
*/
|
||||||
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking
|
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = [], ?Channel $originChannel = null): Booking
|
||||||
{
|
{
|
||||||
$tenant = $property->tenant;
|
$tenant = $property->tenant;
|
||||||
|
|
||||||
@@ -50,7 +57,7 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
|
|||||||
|
|
||||||
return app(TenantContext::class)->run(
|
return app(TenantContext::class)->run(
|
||||||
$tenant,
|
$tenant,
|
||||||
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution),
|
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution, $originChannel),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,9 +65,13 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
|
|||||||
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
|
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
|
||||||
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution
|
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution
|
||||||
*/
|
*/
|
||||||
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution): Booking
|
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution, ?Channel $originChannel): Booking
|
||||||
{
|
{
|
||||||
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): Booking {
|
if ($originChannel !== null && $originChannel->property_id !== $property->id) {
|
||||||
|
throw new ReservationException('Der Kanal gehört nicht zu dieser Wohnung.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution, $originChannel): Booking {
|
||||||
Property::whereKey($property->getKey())->lockForUpdate()->first();
|
Property::whereKey($property->getKey())->lockForUpdate()->first();
|
||||||
|
|
||||||
if (! $this->availability->isAvailable($property, $stay->arrival, $stay->departure)) {
|
if (! $this->availability->isAvailable($property, $stay->arrival, $stay->departure)) {
|
||||||
@@ -70,11 +81,20 @@ private function create(Property $property, StayRequest $stay, array $guestData,
|
|||||||
$quote = $this->calculator->calculate($property, $stay);
|
$quote = $this->calculator->calculate($property, $stay);
|
||||||
|
|
||||||
[$guest, $differences] = $this->guestFor($guestData);
|
[$guest, $differences] = $this->guestFor($guestData);
|
||||||
|
$profile = $originChannel === null && $source === 'website'
|
||||||
|
? app(ProcessSettings::class)->forWebsite($property)
|
||||||
|
: app(ProcessSettings::class)->resolve($property, $originChannel, IntakeKind::Inquiry);
|
||||||
|
$draft = new Booking(['property_id' => $property->id, 'arrival' => $stay->arrival->toDateString(), 'departure' => $stay->departure->toDateString(), 'guests' => $stay->guests]);
|
||||||
|
$draft->setRelation('guest', $guest);
|
||||||
|
$hold = RequestHold::for($draft, $profile);
|
||||||
|
|
||||||
return $property->bookings()->create([
|
return $property->bookings()->create([
|
||||||
|
...$hold,
|
||||||
'guest_id' => $guest->id,
|
'guest_id' => $guest->id,
|
||||||
'status' => BookingStatus::Reserved,
|
'status' => BookingStatus::Reserved,
|
||||||
'source' => $source,
|
'source' => $source,
|
||||||
|
'intake' => IntakeKind::Inquiry,
|
||||||
|
'origin_channel_id' => $originChannel?->id,
|
||||||
...Arr::only(array_filter($attribution), ['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']),
|
...Arr::only(array_filter($attribution), ['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']),
|
||||||
'arrival' => $stay->arrival->toDateString(),
|
'arrival' => $stay->arrival->toDateString(),
|
||||||
'departure' => $stay->departure->toDateString(),
|
'departure' => $stay->departure->toDateString(),
|
||||||
@@ -85,12 +105,21 @@ private function create(Property $property, StayRequest $stay, array $guestData,
|
|||||||
'total' => $quote->total(),
|
'total' => $quote->total(),
|
||||||
'deposit' => $quote->deposit(),
|
'deposit' => $quote->deposit(),
|
||||||
'balance_due_on' => $quote->balanceDueOn->toDateString(),
|
'balance_due_on' => $quote->balanceDueOn->toDateString(),
|
||||||
'hold_expires_at' => $property->pre_reservation_enabled ? now()->addHours($property->hold_hours) : null,
|
|
||||||
'message' => $message,
|
'message' => $message,
|
||||||
'internal_notes' => $differences !== [] ? "Abweichende Angaben in dieser Anfrage (Gästekartei nicht geändert):\n".implode("\n", $differences) : null,
|
'internal_notes' => $differences !== [] ? "Abweichende Angaben in dieser Anfrage (Gästekartei nicht geändert):\n".implode("\n", $differences) : null,
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if ($source === 'website') {
|
||||||
|
// Evidence of what the guest typed (v0.11, S5): completed fields are confirmed, differing ones go to the
|
||||||
|
// landlord as a conflict instead of only a note. The guest record itself was already handled above.
|
||||||
|
$facts = collect(Arr::only($guestData, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']))
|
||||||
|
->filter(fn (?string $value): bool => filled($value))
|
||||||
|
->mapWithKeys(fn (string $value, string $field): array => ['guest.'.$field => $value])->all();
|
||||||
|
app(ContributeCaseFacts::class)->handle($booking, $facts, FactSource::WebsiteForm, ['advance' => false, 'reference' => 'request']);
|
||||||
|
$booking->refresh();
|
||||||
|
}
|
||||||
|
|
||||||
if ($sendMails) {
|
if ($sendMails) {
|
||||||
$this->sendMails($booking);
|
$this->sendMails($booking);
|
||||||
}
|
}
|
||||||
@@ -147,17 +176,21 @@ private function sendMails(Booking $booking): void
|
|||||||
{
|
{
|
||||||
$blockers = [];
|
$blockers = [];
|
||||||
$offerSent = false;
|
$offerSent = false;
|
||||||
|
$asked = false;
|
||||||
|
|
||||||
|
// The process core answers the request as far as its data allows (Architektur V2, trigger request.created):
|
||||||
|
// automatic mode sends the offer or information; if details are missing, the data request asks for them
|
||||||
|
// (and then replaces the receipt) – independently of the offer, which waits for the details.
|
||||||
try {
|
try {
|
||||||
$auto = app(AutoOffer::class);
|
$result = app(ProcessRunner::class)->advance($booking, 'request.created');
|
||||||
if ($auto->applies($booking)) {
|
$offerSent = $result->ran('offer.binding') || $result->ran('offer.information');
|
||||||
$blockers = $auto->handle($booking);
|
$booking->refresh();
|
||||||
$offerSent = $blockers === [];
|
if (! $offerSent && $booking->processingMode() === ProcessingMode::Automatic) {
|
||||||
if (! $offerSent) {
|
$blockers = [...$result->reasons('offer.binding'), ...$result->reasons('offer.information')];
|
||||||
$booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '')."Automatisches Angebot nicht versendet:\n- ".implode("\n- ", $blockers))]);
|
$booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '')."Automatisches Angebot nicht versendet:\n- ".implode("\n- ", $blockers))]);
|
||||||
}
|
}
|
||||||
|
$asked = $result->ran('guest.data_request') && $booking->openDataRequest()?->last_sent_at !== null;
|
||||||
$booking->refresh();
|
$booking->refresh();
|
||||||
}
|
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
Log::warning('Automatisches Angebot fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]);
|
Log::warning('Automatisches Angebot fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||||
$blockers = ['Technischer Fehler beim automatischen Angebot – bitte von Hand bearbeiten.'];
|
$blockers = ['Technischer Fehler beim automatischen Angebot – bitte von Hand bearbeiten.'];
|
||||||
@@ -165,7 +198,7 @@ private function sendMails(Booking $booking): void
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (! $offerSent) {
|
if (! $offerSent && ! $asked && filled($booking->guest?->email)) {
|
||||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
|
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
|
||||||
}
|
}
|
||||||
Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking, $offerSent, $blockers));
|
Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking, $offerSent, $blockers));
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Enums\BookingTaskStatus;
|
||||||
|
use App\Exceptions\ReservationException;
|
||||||
|
use App\Mail\BookingWishAnswered;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingTask;
|
||||||
|
use App\Pricing\StayRequest;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Process\CaseRequirements;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Illuminate\Support\Facades\Mail;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The landlord decides on a booking wish (package 7, "Buchungswunsch bestätigen?"): confirm it – availability is checked
|
||||||
|
* once more under the lock, so two wishes for the same dates can never both become bookings – or decline it with a
|
||||||
|
* friendly answer. The price is the one the guest was told; a lower price of today may be granted, a higher one needs a
|
||||||
|
* new information the guest asks for again.
|
||||||
|
*/
|
||||||
|
class DecideBookingWish
|
||||||
|
{
|
||||||
|
public function __construct(private ConfirmBooking $confirm, private SendOffer $offer) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return bool whether the guest has the confirmation
|
||||||
|
*
|
||||||
|
* @throws ReservationException
|
||||||
|
*/
|
||||||
|
public function confirm(Booking $booking, bool $useTodaysPrice = false, bool $notifyGuest = true): bool
|
||||||
|
{
|
||||||
|
if ($notifyGuest && blank($booking->guest?->email)) {
|
||||||
|
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::transaction(function () use ($booking, $useTodaysPrice): void {
|
||||||
|
$booking->lockForTransition();
|
||||||
|
|
||||||
|
if ($booking->status !== BookingStatus::Reserved || $booking->wish_at === null) {
|
||||||
|
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Buchungswunsch bestätigt');
|
||||||
|
}
|
||||||
|
// G2a also before the binding confirmation of a wish (v0.11, B3), by hand as well.
|
||||||
|
if (($missing = CaseRequirements::blocker($booking->load('guest'), CaseRequirements::WISH_CONFIRMATION)) !== null) {
|
||||||
|
throw new ReservationException($missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($useTodaysPrice) {
|
||||||
|
$quote = $this->offer->quoteFor($booking, new StayRequest($booking->arrival, $booking->departure, $booking->guests, $booking->extras ?? [], $booking->promo_code), (int) $booking->price_adjustment, (string) ($booking->price_adjustment_label ?: 'Zuschlag'));
|
||||||
|
if ($quote->total() > (int) $booking->total) {
|
||||||
|
throw new ReservationException('Der heutige Preis ist höher als der Preis der Auskunft. Ohne Zustimmung des Gastes geht das nicht – bitte eine neue Auskunft senden.');
|
||||||
|
}
|
||||||
|
$booking->update(['quote' => $quote->toArray(), 'total' => $quote->total(), 'deposit' => $quote->deposit(), 'balance_due_on' => $quote->balanceDueOn->toDateString()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->confirm->bind($booking);
|
||||||
|
$booking->update([
|
||||||
|
'accepted_at' => $booking->wish_at,
|
||||||
|
'acceptance' => [
|
||||||
|
'via' => 'booking_wish',
|
||||||
|
'information_version' => $booking->wish['information_version'] ?? $booking->information_version,
|
||||||
|
'wish_at' => $booking->wish_at?->toIso8601String(),
|
||||||
|
'total' => $booking->total,
|
||||||
|
'quote_sha256' => SendInformation::quoteHash($booking),
|
||||||
|
'terms_sha256' => $booking->wish['terms_sha256'] ?? null,
|
||||||
|
'confirmed_by' => CaseLog::actor(),
|
||||||
|
'confirmed_at' => now()->toIso8601String(),
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
$this->closeTasks($booking, 'Bestätigt.');
|
||||||
|
});
|
||||||
|
|
||||||
|
$booking->refresh();
|
||||||
|
CaseLog::record($booking, 'wish', 'Buchungswunsch bestätigt – Buchung verbindlich');
|
||||||
|
|
||||||
|
return $this->confirm->deliver($booking, $notifyGuest);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws ReservationException
|
||||||
|
*/
|
||||||
|
public function decline(Booking $booking, ?string $reason = null, bool $notifyGuest = true): void
|
||||||
|
{
|
||||||
|
DB::transaction(function () use ($booking): void {
|
||||||
|
$booking->lockForTransition();
|
||||||
|
if ($booking->status !== BookingStatus::Reserved) {
|
||||||
|
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgesagt');
|
||||||
|
}
|
||||||
|
$booking->update(['status' => BookingStatus::Declined, 'declined_by' => 'us', 'hold_expires_at' => null]);
|
||||||
|
$this->closeTasks($booking, 'Abgesagt.');
|
||||||
|
});
|
||||||
|
|
||||||
|
CaseLog::record($booking, 'wish', 'Buchungswunsch abgesagt', reason: $reason);
|
||||||
|
|
||||||
|
if ($notifyGuest && filled($booking->guest?->email)) {
|
||||||
|
try {
|
||||||
|
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingWishAnswered($booking->fresh(), 'declined'));
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
Log::warning('Absage zum Buchungswunsch nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function closeTasks(Booking $booking, string $note): void
|
||||||
|
{
|
||||||
|
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->where('status', BookingTaskStatus::Open)->get() as $task) {
|
||||||
|
$task->complete(CaseLog::actor(), $note);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,7 +9,8 @@
|
|||||||
use Illuminate\Support\Facades\Mail;
|
use Illuminate\Support\Facades\Mail;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Marks reservations whose hold time is over as expired and tells the landlord.
|
* Marks reservations whose hold time is over – and information without a hold whose link expired unanswered – as
|
||||||
|
* expired and tells the landlord.
|
||||||
* The calendar already treats them as free once the hold time is over; this only updates the status.
|
* The calendar already treats them as free once the hold time is over; this only updates the status.
|
||||||
*/
|
*/
|
||||||
class ExpireReservations
|
class ExpireReservations
|
||||||
@@ -18,7 +19,12 @@ public function handle(): int
|
|||||||
{
|
{
|
||||||
$expired = Booking::query()
|
$expired = Booking::query()
|
||||||
->whereIn('status', BookingStatus::holding())
|
->whereIn('status', BookingStatus::holding())
|
||||||
->where('hold_expires_at', '<=', now())
|
->where(fn ($query) => $query
|
||||||
|
// A lapsed clarification hold (v0.11) only frees the calendar; the request stays open for its details.
|
||||||
|
->where(fn ($offer) => $offer->where('hold_expires_at', '<=', now())->where('hold_purpose', Booking::HOLD_OFFER))
|
||||||
|
// An information without a hold (package 7) ends when its link expires and the guest did not ask for the booking.
|
||||||
|
->orWhere(fn ($information) => $information->where('status', BookingStatus::Reserved)->whereNull('hold_expires_at')
|
||||||
|
->where('information_valid_until', '<=', now())->whereNull('wish_at')))
|
||||||
->with(['guest', 'property'])
|
->with(['guest', 'property'])
|
||||||
->get();
|
->get();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Communication\Extraction\AccessRejected;
|
||||||
|
use App\Communication\Extraction\AiAccess;
|
||||||
|
use App\Communication\Extraction\ExtractionFailed;
|
||||||
|
use App\Communication\Extraction\MessageExtractor;
|
||||||
|
use App\Communication\Extraction\RiskAssessment;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Enums\BookingTaskStatus;
|
||||||
|
use App\Enums\FactSource;
|
||||||
|
use App\Enums\InboxMessageKind;
|
||||||
|
use App\Enums\TenantServiceKey;
|
||||||
|
use App\Filament\Pages\AiConnection;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingTask;
|
||||||
|
use App\Models\InboundMessage;
|
||||||
|
use App\Models\ServiceUsage;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Support\Inbox;
|
||||||
|
use App\Support\Settings;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The risk-based two-stage extraction of v0.11 (CH-14, E-035): the small model extracts facts with evidence and
|
||||||
|
* confidence, programmatic rules check phase, stored values, contradictions and plausibility, and – when the risk is
|
||||||
|
* high, something contradicts or a check fails – the review model looks at the original and the first extraction.
|
||||||
|
* Only facts that pass every check go to the common fact intake (which applies its own rules); everything else is
|
||||||
|
* proposed to the landlord in the inbox. Wishes to change the stay only become change requests. The extraction
|
||||||
|
* decides nothing binding; without the service, a key or a usable answer the message simply waits for the landlord.
|
||||||
|
*/
|
||||||
|
class ExtractMessageFacts
|
||||||
|
{
|
||||||
|
public function __construct(private MessageExtractor $extractor, private RiskAssessment $risk, private ContributeCaseFacts $facts) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string the extraction status: done, failed or disabled
|
||||||
|
*/
|
||||||
|
public function handle(InboundMessage $message): string
|
||||||
|
{
|
||||||
|
$booking = $message->booking()->with(['guest', 'property'])->first();
|
||||||
|
if ($booking === null || $message->extraction_status !== null) {
|
||||||
|
return (string) $message->extraction_status;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bring your own key: only the landlord's own, complete and not rejected access is used.
|
||||||
|
$access = AiAccess::for(Settings::tenant());
|
||||||
|
if ($access === null) {
|
||||||
|
$message->update(['extraction_status' => 'disabled']);
|
||||||
|
|
||||||
|
return 'disabled';
|
||||||
|
}
|
||||||
|
|
||||||
|
$record = ['prompt_version' => MessageExtractor::promptVersion()];
|
||||||
|
try {
|
||||||
|
$first = $this->extractor->extract($access, $message, $booking);
|
||||||
|
$this->meter();
|
||||||
|
$record['first'] = $first;
|
||||||
|
$data = $first['data'];
|
||||||
|
$checked = $this->risk->facts($booking, (string) $message->body, $data);
|
||||||
|
|
||||||
|
if ($this->risk->needsReview($booking, $checked, $data)) {
|
||||||
|
$review = $this->extractor->review($access, $message, $booking, $data);
|
||||||
|
$this->meter();
|
||||||
|
$record['review'] = $review;
|
||||||
|
$data = $review['data'];
|
||||||
|
$checked = $this->markDisagreements($this->risk->facts($booking, (string) $message->body, $data), $first['data']);
|
||||||
|
}
|
||||||
|
} catch (AccessRejected $exception) {
|
||||||
|
// The access is no longer valid: off for this landlord until he saves or checks it again (no retry loop).
|
||||||
|
AiAccess::markInvalid(Settings::tenant(), $exception->getMessage());
|
||||||
|
app(Inbox::class)->post(InboxMessageKind::AiAccessRejected, 'ai-access', 'KI-Anbindung abgelehnt', $exception->getMessage().' Die automatische Auswertung ist ausgeschaltet, bis Sie den Zugang unter System › KI-Anbindung prüfen. Nachrichten liegen im Posteingang.', actionUrl: AiConnection::getUrl());
|
||||||
|
$message->update(['extraction_status' => 'failed', 'extraction' => [...$record, 'error' => $exception->getMessage()]]);
|
||||||
|
|
||||||
|
return 'failed';
|
||||||
|
} catch (ExtractionFailed $exception) {
|
||||||
|
$message->update(['extraction_status' => 'failed', 'extraction' => [...$record, 'error' => $exception->getMessage()]]);
|
||||||
|
CaseLog::record($booking, 'mail_in', 'Automatische Auswertung nicht möglich – bitte die Nachricht selbst lesen', actor: CaseLog::SYSTEM);
|
||||||
|
|
||||||
|
return 'failed';
|
||||||
|
}
|
||||||
|
|
||||||
|
$automatic = array_values(array_filter($checked, fn (array $fact): bool => $this->risk->mayTakeOver($booking, $fact)));
|
||||||
|
$proposed = array_values(array_filter($checked, fn (array $fact): bool => ! in_array($fact, $automatic, true)));
|
||||||
|
$source = $message->status === InboundMessage::PORTAL ? FactSource::PortalMail : FactSource::Extraction;
|
||||||
|
|
||||||
|
if ($automatic !== []) {
|
||||||
|
$this->facts->handle($booking, collect($automatic)->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['value']])->all(), $source, [
|
||||||
|
'inbound_message_id' => $message->id,
|
||||||
|
'reference' => 'message:'.$message->id,
|
||||||
|
'evidence' => collect($automatic)->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['evidence']])->all(),
|
||||||
|
'confidence' => collect($automatic)->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['confidence']])->all(),
|
||||||
|
'actor' => 'Auswertung der E-Mail (KI, geprüft nach Regeln)',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$changes = $this->changeRequests($booking, $message, $data['change_requests']);
|
||||||
|
$message->update([
|
||||||
|
'extraction_status' => 'done',
|
||||||
|
'extraction' => [...$record, 'intent' => $data['intent'], 'uncertainties' => $data['uncertainties'], 'applied' => $automatic, 'proposed' => $proposed, 'change_requests' => $changes],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->finish($message, $automatic, $proposed, $changes, $data['intent']);
|
||||||
|
|
||||||
|
return 'done';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Facts the two models disagree on are proposed, never taken over.
|
||||||
|
*
|
||||||
|
* @param list<array<string, mixed>> $checked
|
||||||
|
* @param array{facts: list<array{field: string, value: string}>} $first
|
||||||
|
* @return list<array<string, mixed>>
|
||||||
|
*/
|
||||||
|
private function markDisagreements(array $checked, array $first): array
|
||||||
|
{
|
||||||
|
$firstValues = collect($first['facts'])->mapWithKeys(fn (array $fact): array => [$fact['field'] => mb_strtolower(trim($fact['value']))])->all();
|
||||||
|
|
||||||
|
return array_map(function (array $fact) use ($firstValues): array {
|
||||||
|
if (isset($firstValues[$fact['field']]) && $firstValues[$fact['field']] !== mb_strtolower($fact['value'])) {
|
||||||
|
$fact['problems'][] = 'die beiden Modelle lesen den Wert unterschiedlich';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $fact;
|
||||||
|
}, $checked);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wishes to change the stay become change requests through the fact intake (dates, guests) or a task; nothing about
|
||||||
|
* the booking changes (E-038).
|
||||||
|
*
|
||||||
|
* @param list<array{field: string, value: string, evidence: string}> $requests
|
||||||
|
* @return list<array{field: string, value: string, evidence: string}>
|
||||||
|
*/
|
||||||
|
private function changeRequests(Booking $booking, InboundMessage $message, array $requests): array
|
||||||
|
{
|
||||||
|
$kept = array_values(array_filter($requests, fn (array $request): bool => $this->risk->evidenceFound((string) $message->body, $request['evidence'])));
|
||||||
|
$stay = array_filter($kept, fn (array $request): bool => in_array($request['field'], ContributeCaseFacts::STAY_FIELDS, true));
|
||||||
|
if ($stay !== []) {
|
||||||
|
$this->facts->handle($booking, collect($stay)->mapWithKeys(fn (array $request): array => [$request['field'] => $request['value']])->all(), FactSource::Extraction, [
|
||||||
|
'inbound_message_id' => $message->id, 'reference' => 'message-change:'.$message->id, 'advance' => false,
|
||||||
|
'evidence' => collect($stay)->mapWithKeys(fn (array $request): array => [$request['field'] => $request['evidence']])->all(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
foreach (array_filter($kept, fn (array $request): bool => ! in_array($request['field'], ContributeCaseFacts::STAY_FIELDS, true)) as $request) {
|
||||||
|
BookingTask::openOnce($booking, BookingTaskKind::ChangeRequest, 'message:'.$message->id.':'.$request['field'], [
|
||||||
|
'due_on' => today(),
|
||||||
|
'note' => 'Wunsch laut E-Mail ('.$request['field'].'): „'.mb_substr($request['evidence'], 0, 200).'“. Nichts wurde geändert.',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $kept;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array<string, mixed>> $automatic
|
||||||
|
* @param list<array<string, mixed>> $proposed
|
||||||
|
* @param list<array<string, mixed>> $changes
|
||||||
|
*/
|
||||||
|
private function finish(InboundMessage $message, array $automatic, array $proposed, array $changes, string $intent): void
|
||||||
|
{
|
||||||
|
$booking = $message->booking;
|
||||||
|
$task = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::InboundReview)->where('subject', 'm'.$message->id)->where('status', BookingTaskStatus::Open)->first();
|
||||||
|
$parts = array_filter([
|
||||||
|
$automatic !== [] ? count($automatic).' Angabe(n) übernommen' : null,
|
||||||
|
$proposed !== [] ? count($proposed).' Vorschlag/Vorschläge zu prüfen' : null,
|
||||||
|
$changes !== [] ? 'Änderungswunsch erkannt' : null,
|
||||||
|
]);
|
||||||
|
CaseLog::record($booking, 'mail_in', 'E-Mail ausgewertet: '.($parts === [] ? 'keine Angaben erkannt' : implode(', ', $parts)), actor: CaseLog::SYSTEM);
|
||||||
|
|
||||||
|
// Nothing left to look at: a pure answer whose details were all taken over.
|
||||||
|
if ($proposed === [] && $changes === [] && $automatic !== [] && $intent === 'answer') {
|
||||||
|
$task?->forceFill(['status' => BookingTaskStatus::Done, 'completed_at' => now(), 'completed_by' => CaseLog::SYSTEM, 'note' => trim($task->note.' · automatisch ausgewertet')])->save();
|
||||||
|
$message->update(['status' => $message->status === InboundMessage::PORTAL ? InboundMessage::PORTAL : InboundMessage::PROCESSED, 'processed_at' => now()]);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$task?->forceFill(['note' => '„'.mb_substr((string) $message->subject, 0, 120).'“ – '.(implode(', ', $parts) ?: 'keine Angaben erkannt').'. Im Posteingang ansehen.'])->save();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function meter(): void
|
||||||
|
{
|
||||||
|
if (($tenant = Settings::tenant()) !== null) {
|
||||||
|
ServiceUsage::query()->create(['tenant_id' => $tenant->id, 'service' => TenantServiceKey::AiGuestMail->value, 'quantity' => 1, 'used_at' => now()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,90 +2,39 @@
|
|||||||
|
|
||||||
namespace App\Actions;
|
namespace App\Actions;
|
||||||
|
|
||||||
use App\Enums\BookingStatus;
|
|
||||||
use App\Enums\OccupationKind;
|
|
||||||
use App\Exceptions\ReservationException;
|
use App\Exceptions\ReservationException;
|
||||||
use App\Models\BlockedPeriod;
|
use App\Models\BlockedPeriod;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
use App\Models\Guest;
|
|
||||||
use App\Models\Property;
|
|
||||||
use App\Pricing\PortalPrice;
|
|
||||||
use App\Pricing\StayRequest;
|
|
||||||
use App\Tenancy\TenantContext;
|
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Opens the booking file for a reservation that arrived through a portal calendar. The calendar only says "these
|
* Takes over a reservation found in a portal calendar as a case ({@see TakeOverExternalBooking}). The calendar only
|
||||||
* nights are taken"; the file gives the reservation its workflow (contact data, contract, payments, arrival,
|
* says "these nights are taken"; the case gives the reservation its handling. The calendar entry stays as the portal's
|
||||||
* cancellation) like every other booking. The imported calendar entry stays as the portal's mirror of the booking
|
* mirror of the case. A first name from the calendar is no guest identity – it is kept as a note, not as a guest.
|
||||||
* (it keeps its calendar source and UID, but the booking now leads the calendar), the dates stay occupied throughout.
|
|
||||||
*
|
|
||||||
* Unknown facts stay unknown: the guest is a placeholder without contact data, the price is our own calculation (or
|
|
||||||
* empty) until the portal price is entered.
|
|
||||||
*/
|
*/
|
||||||
class OpenPortalFile
|
class OpenPortalFile
|
||||||
{
|
{
|
||||||
public function __construct(private PortalPrice $price) {}
|
public function __construct(private TakeOverExternalBooking $takeOver) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @throws ReservationException
|
* @throws ReservationException
|
||||||
*/
|
*/
|
||||||
public function handle(BlockedPeriod $block): Booking
|
public function handle(BlockedPeriod $block): Booking
|
||||||
{
|
{
|
||||||
return DB::transaction(function () use ($block): Booking {
|
if ($block->channel === null) {
|
||||||
Property::query()->whereKey($block->property_id)->lockForUpdate()->firstOrFail();
|
throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.');
|
||||||
$block = BlockedPeriod::query()->whereKey($block->id)->lockForUpdate()->firstOrFail();
|
|
||||||
|
|
||||||
if (! in_array($block->source, ['channel', 'email'], true) || $block->channel_id === null) {
|
|
||||||
throw new ReservationException('Eine Akte gibt es nur für Reservierungen aus einem Portalkalender.');
|
|
||||||
}
|
|
||||||
if ($block->occupationKind() === OccupationKind::Block) {
|
|
||||||
throw new ReservationException('Eine Sperrzeit ist keine Reservierung. Bitte zuerst „Einordnen“ und als Portalreservierung kennzeichnen.');
|
|
||||||
}
|
|
||||||
if ($block->is_representation && $block->linked_booking_id !== null) {
|
|
||||||
return Booking::query()->findOrFail($block->linked_booking_id);
|
|
||||||
}
|
|
||||||
if ($block->is_representation) {
|
|
||||||
throw new ReservationException('Dieser Eintrag ist die Spiegelung einer anderen Belegung. Die Akte gehört an die führende Belegung.');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$property = $block->property;
|
|
||||||
$channel = $block->channel;
|
|
||||||
$fields = (array) ($block->ical_interpretation['fields'] ?? []);
|
$fields = (array) ($block->ical_interpretation['fields'] ?? []);
|
||||||
$guest = $block->guest ?? Guest::query()->create([
|
$name = trim((string) ($fields['guest_first_name'] ?? ''));
|
||||||
'first_name' => filled($fields['guest_first_name'] ?? null) ? (string) $fields['guest_first_name'] : 'Gast',
|
|
||||||
'last_name' => '('.$channel->name.')',
|
|
||||||
'email' => '',
|
|
||||||
'tenant_id' => app(TenantContext::class)->id(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
$stay = new StayRequest(CarbonImmutable::parse($block->starts_on), CarbonImmutable::parse($block->ends_on), min(2, $property->max_guests));
|
return $this->takeOver->handle(
|
||||||
$booking = $property->bookings()->create([
|
$block->property,
|
||||||
'guest_id' => $guest->id,
|
$block->channel,
|
||||||
'status' => BookingStatus::Reserved,
|
CarbonImmutable::parse($block->starts_on),
|
||||||
'source' => 'portal',
|
CarbonImmutable::parse($block->ends_on),
|
||||||
'origin_channel_id' => $block->origin_channel_id ?? $channel->id,
|
['notes' => 'Aus dem Portalkalender „'.$block->channel->name.'“ übernommen.'.($name !== '' ? ' Name laut Kalender: '.$name.'.' : '')],
|
||||||
'portal_reference' => $fields['booking_reference'] ?? null,
|
$block,
|
||||||
'arrival' => $stay->arrival->toDateString(),
|
);
|
||||||
'departure' => $stay->departure->toDateString(),
|
|
||||||
'guests' => $stay->guests,
|
|
||||||
'hold_expires_at' => null,
|
|
||||||
'internal_notes' => 'Akte aus dem Portalkalender „'.$channel->name.'“ angelegt. Personenzahl und Preis sind nicht bekannt – bitte den Portalpreis erfassen.',
|
|
||||||
...$this->price->unknownColumns($property, $stay),
|
|
||||||
]);
|
|
||||||
|
|
||||||
$block->forceFill([
|
|
||||||
'is_representation' => true, 'representation_automatic' => false, 'canonical_block_id' => null,
|
|
||||||
'linked_booking_id' => $booking->id, 'export_approved' => false, 'needs_review' => false, 'reviewed_at' => now(),
|
|
||||||
'occupation_kind' => OccupationKind::Reservation, 'guest_id' => $guest->id,
|
|
||||||
'review_note' => 'Akte angelegt; die Buchung führt diese Belegung.',
|
|
||||||
])->save();
|
|
||||||
|
|
||||||
app(ConfirmBooking::class)->bind($booking);
|
|
||||||
app(ReconcileChannelRepresentations::class)->handle($property);
|
|
||||||
|
|
||||||
return $booking->refresh();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Enums\BookingTaskStatus;
|
||||||
|
use App\Enums\InternalKind;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingTask;
|
||||||
|
use App\Models\Extra;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Package 9, P04: prepares the stays of the coming two weeks – once per case and task, however often it runs.
|
||||||
|
*
|
||||||
|
* - **Arrival details:** a few days before the arrival information is due, a task asks for what is missing (a way to
|
||||||
|
* reach the guest; the arrival time where the property asks for it). It closes itself once the data is there. For a
|
||||||
|
* portal booking the contact may have to be fetched from the portal.
|
||||||
|
* - **Stay tasks of the property:** cleaning, linen, key handover … as configured on the property, with their due date.
|
||||||
|
* - **Booked services:** every extra of our own price (or of a private stay) becomes a task to provide it.
|
||||||
|
*
|
||||||
|
* Nothing is sent to guests here; the arrival information keeps going out by itself where we are responsible.
|
||||||
|
*/
|
||||||
|
class PrepareStays
|
||||||
|
{
|
||||||
|
/** How far ahead stays are prepared. */
|
||||||
|
public const LEAD_DAYS = 14;
|
||||||
|
|
||||||
|
/** Days before the arrival information that the arrival details are checked. */
|
||||||
|
private const DETAILS_BEFORE_INFO = 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{arrival_details: int, stay_tasks: int}
|
||||||
|
*/
|
||||||
|
public function handle(): array
|
||||||
|
{
|
||||||
|
$today = CarbonImmutable::today();
|
||||||
|
$created = ['arrival_details' => 0, 'stay_tasks' => 0];
|
||||||
|
|
||||||
|
$stays = Booking::query()
|
||||||
|
->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid])
|
||||||
|
->whereDate('arrival', '<=', $today->addDays(self::LEAD_DAYS))
|
||||||
|
->whereDate('departure', '>=', $today)
|
||||||
|
->with(['guest', 'property', 'importChannel', 'originChannel'])
|
||||||
|
->get();
|
||||||
|
|
||||||
|
foreach ($stays as $booking) {
|
||||||
|
$created['arrival_details'] += $this->arrivalDetails($booking, $today) ? 1 : 0;
|
||||||
|
$created['stay_tasks'] += $this->stayTasks($booking);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $created;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What is still missing for the arrival, in plain words (empty: nothing).
|
||||||
|
*
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public static function missingArrivalDetails(Booking $booking): array
|
||||||
|
{
|
||||||
|
if ($booking->isInternal()) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values(array_filter([
|
||||||
|
$booking->guest === null ? 'Name und Kontakt des Gastes' : null,
|
||||||
|
$booking->guest !== null && blank($booking->guest->email) && blank($booking->guest->phone) ? 'eine E-Mail-Adresse oder Telefonnummer des Gastes' : null,
|
||||||
|
$booking->property?->asks_arrival_time && blank($booking->arrival_time) ? 'die Anreisezeit' : null,
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens (or closes) the task for missing arrival details.
|
||||||
|
*/
|
||||||
|
private function arrivalDetails(Booking $booking, CarbonImmutable $today): bool
|
||||||
|
{
|
||||||
|
$missing = self::missingArrivalDetails($booking);
|
||||||
|
$open = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::ArrivalDetails)->where('status', BookingTaskStatus::Open)->first();
|
||||||
|
|
||||||
|
if ($missing === []) {
|
||||||
|
$open?->complete(CaseLog::SYSTEM, 'Die Angaben liegen jetzt vor.');
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$checkFrom = $booking->arrival->subDays($booking->process()->arrivalInfoDaysBefore() + self::DETAILS_BEFORE_INFO);
|
||||||
|
if ($today->lessThan($checkFrom)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$portal = $booking->caseType()->isExternallyBinding() ? ' (ggf. im Portal '.($booking->processChannel()?->name ?? '').' nachsehen)' : '';
|
||||||
|
$task = BookingTask::openOnce($booking, BookingTaskKind::ArrivalDetails, '', [
|
||||||
|
'due_on' => $booking->arrival->subDays($booking->process()->arrivalInfoDaysBefore()),
|
||||||
|
'note' => 'Es fehlt: '.implode(', ', $missing).$portal.'.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $task->wasRecentlyCreated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens the configured stay tasks and the tasks for booked services; returns how many were opened now.
|
||||||
|
*/
|
||||||
|
private function stayTasks(Booking $booking): int
|
||||||
|
{
|
||||||
|
$kind = match (true) {
|
||||||
|
! $booking->isInternal() => 'rental',
|
||||||
|
$booking->internal_kind === InternalKind::PrivateStay => 'private',
|
||||||
|
$booking->internal_kind === InternalKind::OwnUse => 'own',
|
||||||
|
default => 'block',
|
||||||
|
};
|
||||||
|
$opened = 0;
|
||||||
|
|
||||||
|
foreach ($booking->property?->stayTaskDefinitions() ?? [] as $definition) {
|
||||||
|
if (! in_array($kind, $definition['applies_to'], true)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$due = match ($definition['when']) {
|
||||||
|
'after_departure' => $booking->departure,
|
||||||
|
'on_arrival' => $booking->arrival,
|
||||||
|
default => $booking->arrival->subDays($definition['days']),
|
||||||
|
};
|
||||||
|
$task = BookingTask::openOnce($booking, BookingTaskKind::Service, $definition['key'], [
|
||||||
|
'title' => $definition['title'],
|
||||||
|
'responsible' => $definition['responsible'],
|
||||||
|
'due_on' => $due,
|
||||||
|
]);
|
||||||
|
// Dates of the stay may have changed since the task was opened.
|
||||||
|
if (! $task->wasRecentlyCreated && $task->status === BookingTaskStatus::Open && ! $task->due_on?->equalTo($due)) {
|
||||||
|
$task->update(['due_on' => $due]);
|
||||||
|
}
|
||||||
|
$opened += $task->wasRecentlyCreated ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Booked services of our own price (a portal's extras are not known item by item).
|
||||||
|
if (($booking->quote['source'] ?? null) !== 'portal') {
|
||||||
|
$extras = array_filter((array) ($booking->extras ?? []), fn ($quantity): bool => (int) $quantity > 0);
|
||||||
|
foreach (Extra::query()->whereIn('id', array_keys($extras))->get() as $extra) {
|
||||||
|
$task = BookingTask::openOnce($booking, BookingTaskKind::Service, 'extra:'.$extra->id, [
|
||||||
|
'title' => 'Bereitstellen: '.((int) $extras[$extra->id] > 1 ? $extras[$extra->id].' × ' : '').$extra->name,
|
||||||
|
'due_on' => $booking->arrival->subDay(),
|
||||||
|
]);
|
||||||
|
$opened += $task->wasRecentlyCreated ? 1 : 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $opened;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Actions;
|
namespace App\Actions;
|
||||||
|
|
||||||
use App\Channels\ConflictDetector;
|
use App\Channels\ConflictDetector;
|
||||||
|
use App\Channels\Intake\PortalIntake;
|
||||||
use App\Channels\Mail\ParsedPortalMail;
|
use App\Channels\Mail\ParsedPortalMail;
|
||||||
use App\Channels\Mail\PortalMail;
|
use App\Channels\Mail\PortalMail;
|
||||||
use App\Channels\Mail\PortalMailParser;
|
use App\Channels\Mail\PortalMailParser;
|
||||||
@@ -11,8 +12,11 @@
|
|||||||
use App\Enums\TenantServiceKey;
|
use App\Enums\TenantServiceKey;
|
||||||
use App\Mail\PortalMailNotification;
|
use App\Mail\PortalMailNotification;
|
||||||
use App\Models\BlockedPeriod;
|
use App\Models\BlockedPeriod;
|
||||||
|
use App\Models\Booking;
|
||||||
use App\Models\Channel;
|
use App\Models\Channel;
|
||||||
|
use App\Models\IntakeObservation;
|
||||||
use App\Models\PortalEmail;
|
use App\Models\PortalEmail;
|
||||||
|
use App\Process\ProcessRunner;
|
||||||
use App\Support\Settings;
|
use App\Support\Settings;
|
||||||
use App\Tenancy\TenantFeatures;
|
use App\Tenancy\TenantFeatures;
|
||||||
use Carbon\CarbonInterface;
|
use Carbon\CarbonInterface;
|
||||||
@@ -75,6 +79,10 @@ 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));
|
||||||
|
rescue(fn () => $this->resume($channel, $parsed, $record));
|
||||||
|
|
||||||
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
|
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
|
||||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record)));
|
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record)));
|
||||||
}
|
}
|
||||||
@@ -86,6 +94,33 @@ public function handle(PortalMail $mail): ?PortalEmail
|
|||||||
return $record;
|
return $record;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A booking mail of the portal can be the confirmation a case waits for (V2.1, docs/Prozessarchitektur/V2.1/02 §5): the
|
||||||
|
* case is evaluated again. Only cases whose channel makes them wait are touched – everything else stays as it was.
|
||||||
|
*/
|
||||||
|
private function resume(Channel $channel, ParsedPortalMail $parsed, PortalEmail $record): void
|
||||||
|
{
|
||||||
|
if ($parsed->type !== PortalEmailType::Booking) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$case = $record->blocked_period_id !== null ? Booking::query()->find(BlockedPeriod::withTrashed()->whereKey($record->blocked_period_id)->value('linked_booking_id')) : null;
|
||||||
|
$case ??= $parsed->reference !== null ? app(PortalIntake::class)->caseByReference($channel, $parsed->reference) : null;
|
||||||
|
if ($case !== null && $case->isBinding() && $case->process()->awaitsPortalConfirmation()) {
|
||||||
|
app(ProcessRunner::class)->advance($case, 'portal.mail');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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.
|
* Channels list the sender addresses or domains of their notification e-mails in settings.email_senders.
|
||||||
*/
|
*/
|
||||||
@@ -177,6 +212,11 @@ private function release(Channel $channel, ParsedPortalMail $parsed): array
|
|||||||
default => null,
|
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) {
|
if ($block) {
|
||||||
$block->delete();
|
$block->delete();
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,14 @@
|
|||||||
namespace App\Actions;
|
namespace App\Actions;
|
||||||
|
|
||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\FactSource;
|
||||||
|
use App\Enums\IntakeKind;
|
||||||
|
use App\Enums\ProcessingMode;
|
||||||
use App\Exceptions\ReservationException;
|
use App\Exceptions\ReservationException;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
use App\Support\BookingProgress;
|
use App\Models\Guest;
|
||||||
use Illuminate\Support\Arr;
|
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
|
* The guest's contact data arrived (portal message, e-mail, phone) and is entered on the booking. The landlord chooses
|
||||||
@@ -19,7 +23,7 @@ class ProvideGuestContact
|
|||||||
|
|
||||||
public const MANUAL = 'manual';
|
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
|
* @param array<string, ?string> $contact first_name, last_name, email, phone, street, postal_code, city, country
|
||||||
@@ -38,9 +42,15 @@ public function handle(Booking $booking, array $contact, string $process = self:
|
|||||||
throw new ReservationException('Für den automatischen Ablauf wird die E-Mail-Adresse des Gastes benötigt.');
|
throw new ReservationException('Für den automatischen Ablauf wird die E-Mail-Adresse des Gastes benötigt.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$booking->guest->update(array_filter($contact, fn ($value) => $value !== null));
|
if ($booking->guest === null && (blank($contact['first_name'] ?? null) || blank($contact['last_name'] ?? null))) {
|
||||||
|
throw new ReservationException('Bitte Vor- und Nachnamen des Gastes angeben.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// The landlord's entry goes through the common fact intake (v0.11, S5): taken over with its source, the previous
|
||||||
|
// value kept as evidence. Carrying on stays with the choice below.
|
||||||
|
app(ContributeCaseFacts::class)->handle($booking, collect($contact)->mapWithKeys(fn (?string $value, string $field): array => ['guest.'.$field => $value])->all(), FactSource::Landlord, ['advance' => false, 'reference' => 'landlord:'.now()->getTimestampMs()]);
|
||||||
if ($guestConfirmed) {
|
if ($guestConfirmed) {
|
||||||
$booking->forceFill(['guest_confirmed_at' => $booking->guest_confirmed_at ?? now()])->saveQuietly();
|
$booking->forceFill(['guest_confirmed_at' => $booking->guest_confirmed_at ?? now()])->save();
|
||||||
}
|
}
|
||||||
$booking->refresh()->load('guest');
|
$booking->refresh()->load('guest');
|
||||||
|
|
||||||
@@ -48,19 +58,31 @@ public function handle(Booking $booking, array $contact, string $process = self:
|
|||||||
return 'Kontaktdaten gespeichert';
|
return 'Kontaktdaten gespeichert';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$booking->update(['processing_mode' => ProcessingMode::Automatic]);
|
||||||
|
|
||||||
if (in_array($booking->status, BookingStatus::occupying(), true)) {
|
if (in_array($booking->status, BookingStatus::occupying(), true)) {
|
||||||
$this->confirm->deliver($booking);
|
$reasons = $this->documents->automatically($booking);
|
||||||
|
if ($reasons !== []) {
|
||||||
return 'Kontaktdaten gespeichert, Vertrag gesendet';
|
throw new ReservationException('Kontaktdaten gespeichert. Die Unterlagen werden noch nicht automatisch versendet: '.implode(' ', $reasons));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (BookingProgress::kind($booking) === BookingProgress::PORTAL_BOOKING) {
|
return 'Kontaktdaten gespeichert, Unterlagen gesendet';
|
||||||
$this->confirm->handle($booking);
|
|
||||||
|
|
||||||
return 'Kontaktdaten gespeichert, Buchung bestätigt und Vertrag gesendet';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->offer->handle($booking);
|
if ($booking->intake === IntakeKind::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 Unterlagen gesendet';
|
||||||
|
}
|
||||||
|
|
||||||
|
$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';
|
return 'Kontaktdaten gespeichert, Angebot gesendet';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Channels\Mail\PortalMail;
|
||||||
|
use App\Communication\MessageMatcher;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Models\BookingTask;
|
||||||
|
use App\Models\InboundMessage;
|
||||||
|
use App\Models\Mailbox;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Support\Settings;
|
||||||
|
use Illuminate\Database\UniqueConstraintViolationException;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The inbox of v0.11 (S2/S3, CH-01, CH-06, CH-08): every message of the landlord's dedicated mailbox is stored first,
|
||||||
|
* once per Message-ID. Booking notifications of the portals go unchanged through the existing portal path; every other
|
||||||
|
* message is assigned to a case by the deterministic rules or waits in the inbox for the landlord. A message never
|
||||||
|
* creates a case by itself. An assigned reply stops the reminders of the case's data request; its details are taken
|
||||||
|
* over only through the extraction and the common fact intake.
|
||||||
|
*/
|
||||||
|
class ReceiveInboundMessage
|
||||||
|
{
|
||||||
|
public function __construct(private ProcessPortalMail $portalMail, private MessageMatcher $matcher, private RequestCaseData $requests) {}
|
||||||
|
|
||||||
|
public function handle(PortalMail $mail, ?Mailbox $mailbox = null): InboundMessage
|
||||||
|
{
|
||||||
|
$existing = InboundMessage::query()->where('message_id', $mail->messageId)->first();
|
||||||
|
if ($existing !== null) {
|
||||||
|
return $existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$message = InboundMessage::query()->create([
|
||||||
|
'mailbox_id' => $mailbox?->id,
|
||||||
|
'message_id' => $mail->messageId,
|
||||||
|
'in_reply_to' => $mail->inReplyTo,
|
||||||
|
'references' => $mail->references,
|
||||||
|
'from_address' => mb_strtolower($mail->from),
|
||||||
|
'from_name' => $mail->fromName,
|
||||||
|
'to_addresses' => $mail->to,
|
||||||
|
'subject' => mb_substr($mail->subject, 0, 500),
|
||||||
|
'body' => $mail->text,
|
||||||
|
'received_at' => $mail->receivedAt,
|
||||||
|
// CH §5 / M10: what arrives in test operation is marked as such.
|
||||||
|
'test_mode' => ! Settings::isLive(),
|
||||||
|
'status' => InboundMessage::NEW,
|
||||||
|
]);
|
||||||
|
} catch (UniqueConstraintViolationException) {
|
||||||
|
return InboundMessage::query()->where('message_id', $mail->messageId)->firstOrFail();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->portalMail->channelFor($mail->from) !== null) {
|
||||||
|
// A portal's notification: the existing portal path decides, unchanged (CH-08).
|
||||||
|
$record = $this->portalMail->handle($mail);
|
||||||
|
$record?->forceFill(['inbound_message_id' => $message->id])->save();
|
||||||
|
// CH-09/12: if the notification belongs to a case, the guest details it carries are evaluated for that case.
|
||||||
|
$bookingId = $record?->blockedPeriod()->value('linked_booking_id');
|
||||||
|
$message->update(['status' => InboundMessage::PORTAL, 'portal_email_id' => $record?->id, 'booking_id' => $bookingId, 'match_reason' => $bookingId ? 'portal_reference' : null, 'processed_at' => now()]);
|
||||||
|
|
||||||
|
return $message;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->isOwn($mail, $mailbox)) {
|
||||||
|
$message->update(['status' => InboundMessage::IGNORED, 'match_reason' => 'own', 'processed_at' => now()]);
|
||||||
|
|
||||||
|
return $message;
|
||||||
|
}
|
||||||
|
|
||||||
|
$match = $this->matcher->match($message);
|
||||||
|
if ($match['booking'] === null) {
|
||||||
|
$message->update(['status' => InboundMessage::NEEDS_REVIEW, 'hints' => $match['hints']]);
|
||||||
|
|
||||||
|
return $message;
|
||||||
|
}
|
||||||
|
|
||||||
|
$booking = $match['booking'];
|
||||||
|
$message->update(['status' => InboundMessage::ASSIGNED, 'booking_id' => $booking->id, 'match_reason' => $match['reason']]);
|
||||||
|
CaseLog::record($booking, 'mail_in', 'E-Mail des Gastes eingegangen'.($message->test_mode ? ' (im Testbetrieb)' : '').': '.$message->subject, actor: CaseLog::GUEST, at: $message->received_at);
|
||||||
|
$this->requests->replyReceived($booking);
|
||||||
|
BookingTask::openOnce($booking, BookingTaskKind::InboundReview, 'm'.$message->id, ['due_on' => today(), 'note' => '„'.mb_substr((string) $message->subject, 0, 120).'“ – im Posteingang ansehen; erkannte Angaben werden dort zur Übernahme vorgeschlagen.']);
|
||||||
|
// Evaluate at once instead of waiting for the next five-minute run (the run remains the safety net).
|
||||||
|
$this->evaluate($message);
|
||||||
|
|
||||||
|
return $message->refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs the extraction for a freshly assigned message; a problem never undoes the assignment.
|
||||||
|
*/
|
||||||
|
public function evaluate(InboundMessage $message): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
app(ExtractMessageFacts::class)->handle($message->refresh());
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
report($exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Our own mails (copies, loops) are not guest messages.
|
||||||
|
*/
|
||||||
|
private function isOwn(PortalMail $mail, ?Mailbox $mailbox): bool
|
||||||
|
{
|
||||||
|
$own = array_filter(array_map(fn (?string $address): string => mb_strtolower(trim((string) $address)), [
|
||||||
|
$mailbox?->address, config('mail.from.address'), Settings::tenant()?->sender_email,
|
||||||
|
]));
|
||||||
|
|
||||||
|
return in_array(mb_strtolower($mail->from), $own, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,52 +3,125 @@
|
|||||||
namespace App\Actions;
|
namespace App\Actions;
|
||||||
|
|
||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Enums\BookingTaskStatus;
|
||||||
|
use App\Enums\PaymentKind;
|
||||||
use App\Enums\PaymentMethod;
|
use App\Enums\PaymentMethod;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingTask;
|
||||||
use App\Models\Payment;
|
use App\Models\Payment;
|
||||||
|
use App\Pricing\CaseMoney;
|
||||||
|
use App\Process\CaseClosure;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Support\Money;
|
||||||
use Carbon\CarbonInterface;
|
use Carbon\CarbonInterface;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Records a received payment (or a refund with a negative amount) and moves the booking along:
|
* Records a payment of a case with its kind (package 8): the guest paid us, the portal reports the guest paid it, the
|
||||||
* Bestätigt → Anzahlung erhalten → Bezahlt.
|
* portal paid out to us, or we refunded the guest. A refund is stored as a negative amount.
|
||||||
|
*
|
||||||
|
* Only money of the guest that arrived on our account moves the booking along (Bestätigt → Anzahlung erhalten →
|
||||||
|
* Bezahlt). "Paid according to the portal" and a payout of the portal are facts of their own: they appear in the money
|
||||||
|
* overview and the history with their own words, never as "Anzahlung erhalten" (package 9, Abschnitt 5).
|
||||||
*/
|
*/
|
||||||
class RecordPayment
|
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;
|
||||||
|
|
||||||
|
$payment = DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy, $kind, $source): Payment {
|
||||||
$payment = $booking->payments()->create([
|
$payment = $booking->payments()->create([
|
||||||
'amount' => $amount,
|
'amount' => $amount,
|
||||||
'paid_on' => $paidOn->toDateString(),
|
'paid_on' => $paidOn->toDateString(),
|
||||||
'method' => $method,
|
'method' => $method,
|
||||||
'note' => $note,
|
'note' => $note,
|
||||||
'recorded_by' => $recordedBy,
|
'recorded_by' => $recordedBy,
|
||||||
|
'kind' => $kind,
|
||||||
|
'source' => $source,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$booking->unsetRelation('payments');
|
$booking->unsetRelation('payments');
|
||||||
$this->updateStatus($booking);
|
$this->updateStatus($booking);
|
||||||
|
$this->settleTasks($booking, $kind, $recordedBy ?? CaseLog::actor());
|
||||||
|
|
||||||
return $payment;
|
return $payment;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
CaseClosure::refresh($booking->fresh());
|
||||||
|
|
||||||
|
return $payment;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function updateStatus(Booking $booking): void
|
public function updateStatus(Booking $booking): void
|
||||||
{
|
{
|
||||||
$paymentStatuses = [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid];
|
$status = self::statusFor($booking);
|
||||||
if (! in_array($booking->status, $paymentStatuses, true)) {
|
if ($status !== null && $status !== $booking->status) {
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$paid = $booking->paidAmount();
|
|
||||||
$status = match (true) {
|
|
||||||
$paid >= $booking->total => BookingStatus::Paid,
|
|
||||||
$paid >= $booking->deposit && $paid > 0 => BookingStatus::DepositPaid,
|
|
||||||
default => BookingStatus::Confirmed,
|
|
||||||
};
|
|
||||||
|
|
||||||
if ($status !== $booking->status) {
|
|
||||||
$booking->update(['status' => $status]);
|
$booking->update(['status' => $status]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The payment status the booking should have by the guest's money on our account, or null when payments do not move
|
||||||
|
* this booking (not binding, closed, cancelled).
|
||||||
|
*/
|
||||||
|
public static function statusFor(Booking $booking): ?BookingStatus
|
||||||
|
{
|
||||||
|
if (! in_array($booking->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$paid = $booking->paidToUs();
|
||||||
|
|
||||||
|
return match (true) {
|
||||||
|
$booking->total !== null && $booking->total > 0 && $paid >= $booking->total => BookingStatus::Paid,
|
||||||
|
$booking->deposit !== null && $paid >= $booking->deposit && $paid > 0 => BookingStatus::DepositPaid,
|
||||||
|
default => BookingStatus::Confirmed,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The history line in the words of what really happened.
|
||||||
|
*/
|
||||||
|
public static function summary(Booking $booking, PaymentKind $kind, int $amount, CarbonInterface $paidOn, ?string $source): string
|
||||||
|
{
|
||||||
|
$portal = $source ?: ($booking->processChannel()?->name ?? 'Portal');
|
||||||
|
|
||||||
|
return match ($kind) {
|
||||||
|
PaymentKind::Guest => 'Zahlung des Gastes auf unserem Konto eingegangen: '.Money::format($amount),
|
||||||
|
PaymentKind::GuestViaPortal => 'Laut '.$portal.' hat der Gast '.Money::format($amount).' an das Portal gezahlt – noch kein Geld bei uns',
|
||||||
|
PaymentKind::PortalPayout => 'Auszahlung von '.$portal.' auf unserem Konto eingegangen: '.Money::format($amount),
|
||||||
|
PaymentKind::Refund => 'Erstattung an den Gast: '.Money::format(abs($amount)),
|
||||||
|
}.' (vom '.$paidOn->format('d.m.Y').')';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tasks that the payment settles: the payout check once nothing is outstanding, the claim after the stay once the
|
||||||
|
* guest owes nothing more.
|
||||||
|
*/
|
||||||
|
private function settleTasks(Booking $booking, PaymentKind $kind, string $by): void
|
||||||
|
{
|
||||||
|
$money = CaseMoney::of($booking);
|
||||||
|
$open = fn (BookingTaskKind $taskKind) => BookingTask::query()->where('booking_id', $booking->id)->where('kind', $taskKind)->where('status', BookingTaskStatus::Open)->get();
|
||||||
|
|
||||||
|
if ($kind === PaymentKind::PortalPayout) {
|
||||||
|
$payout = $money->payout();
|
||||||
|
if (($payout['outstanding'] ?? 0) === 0) {
|
||||||
|
$open(BookingTaskKind::PayoutCheck)->each->complete($by, 'Auszahlung erfasst: '.Money::format($payout['received']).'.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_array($kind, [PaymentKind::Guest, PaymentKind::GuestViaPortal], true)) {
|
||||||
|
// A reminder that is no longer needed is closed by the payment itself.
|
||||||
|
if ($booking->openDeposit() === 0) {
|
||||||
|
$open(BookingTaskKind::DepositReminder)->each->complete($by, 'Anzahlung eingegangen.');
|
||||||
|
}
|
||||||
|
if ($booking->openAmount() === 0) {
|
||||||
|
foreach ([BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder, BookingTaskKind::OpenClaim] as $settled) {
|
||||||
|
$open($settled)->each->complete($by, 'Betrag vollständig erhalten.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Enums\AmountKind;
|
||||||
|
use App\Enums\PaymentKind;
|
||||||
|
use App\Enums\PaymentMethod;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Pricing\PortalPrice;
|
||||||
|
use App\Process\CaseAutomation;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Support\Money;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Takes over what a portal shows about a booking (package 8): the guest's total as the agreed price ("Gesamtpreis laut
|
||||||
|
* Portal"), and – as far as the portal shows them – price positions, collective amounts, commission, announced payouts,
|
||||||
|
* instalments and what the guest has paid to the portal. Every value is stored with its source and date as stated; the
|
||||||
|
* total is never recalculated from the positions, and a statement entered twice is stored once.
|
||||||
|
*/
|
||||||
|
class RecordPortalAmounts
|
||||||
|
{
|
||||||
|
public function __construct(private PortalPrice $price, private RecordPayment $payments) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{kind: AmountKind|string, label?: ?string, amount: int, due_on?: ?string, note?: ?string}> $amounts
|
||||||
|
* @param list<array{amount: int, paid_on: string}> $paidViaPortal instalments the portal shows as paid by the guest
|
||||||
|
*/
|
||||||
|
public function handle(Booking $booking, ?int $guestTotal, array $amounts, array $paidViaPortal, string $source, ?CarbonImmutable $statedOn = null, ?string $by = null): void
|
||||||
|
{
|
||||||
|
$statedOn ??= CarbonImmutable::today();
|
||||||
|
|
||||||
|
DB::transaction(function () use ($booking, $guestTotal, $amounts, $paidViaPortal, $source, $statedOn, $by): void {
|
||||||
|
if ($guestTotal !== null && $guestTotal !== $booking->total) {
|
||||||
|
$before = $booking->total;
|
||||||
|
$booking->update($this->price->columns($booking->property, $booking->arrival, $booking->departure, $booking->guests, $guestTotal, $source));
|
||||||
|
CaseLog::record($booking, 'price', 'Gesamtpreis laut '.$source.': '.Money::format($guestTotal).($before !== null ? ' (vorher '.Money::format($before).')' : ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($amounts as $row) {
|
||||||
|
$kind = $row['kind'] instanceof AmountKind ? $row['kind'] : AmountKind::from((string) $row['kind']);
|
||||||
|
$label = filled($row['label'] ?? null) ? trim((string) $row['label']) : null;
|
||||||
|
$exists = $booking->amounts()->where('kind', $kind)->where('amount', (int) $row['amount'])->where('source', $source)
|
||||||
|
->where(fn ($query) => $label === null ? $query->whereNull('label') : $query->where('label', $label))->exists();
|
||||||
|
if ($exists) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$booking->amounts()->create([
|
||||||
|
'kind' => $kind, 'label' => $label, 'amount' => (int) $row['amount'], 'source' => $source,
|
||||||
|
'stated_on' => $statedOn->toDateString(), 'due_on' => filled($row['due_on'] ?? null) ? $row['due_on'] : null,
|
||||||
|
'note' => filled($row['note'] ?? null) ? trim((string) $row['note']) : null, 'recorded_by' => $by,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($paidViaPortal as $row) {
|
||||||
|
$paidOn = CarbonImmutable::parse($row['paid_on']);
|
||||||
|
$known = $booking->payments()->where('kind', PaymentKind::GuestViaPortal)->where('amount', (int) $row['amount'])->whereDate('paid_on', $paidOn)->exists();
|
||||||
|
if (! $known) {
|
||||||
|
$this->payments->handle($booking, (int) $row['amount'], $paidOn, PaymentMethod::Other, 'laut '.$source, $by, PaymentKind::GuestViaPortal, $source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app(CaseAutomation::class)->advance($booking->fresh());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Actions;
|
|
||||||
|
|
||||||
use App\Exceptions\ReservationException;
|
|
||||||
use App\Models\Booking;
|
|
||||||
use App\Models\Channel;
|
|
||||||
use App\Models\Property;
|
|
||||||
use App\Pricing\PortalPrice;
|
|
||||||
use App\Pricing\QuoteException;
|
|
||||||
use App\Pricing\StayRequest;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records a booking that a portal already made binding (e.g. a direct booking on FeWo-direkt) – usually without
|
|
||||||
* the guest's contact data. The booking keeps the portal as its origin channel and may carry the portal's price and
|
|
||||||
* reference. The landlord decides how the contract process continues:
|
|
||||||
*
|
|
||||||
* - {@see self::CONFIRM}: the booking becomes binding right away (the dates are occupied), the contract follows
|
|
||||||
* once the contact data is known ({@see ProvideGuestContact}) – no contract is generated before that;
|
|
||||||
* - {@see self::CONTRACT}: binding and contract mail at once (needs the guest's e-mail address);
|
|
||||||
* - {@see self::RECORD}: only recorded as a request, everything else is done by hand.
|
|
||||||
*/
|
|
||||||
class RecordPortalBooking
|
|
||||||
{
|
|
||||||
public const CONFIRM = 'confirm';
|
|
||||||
|
|
||||||
public const CONTRACT = 'contract';
|
|
||||||
|
|
||||||
public const RECORD = 'record';
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
private CreateReservation $create,
|
|
||||||
private ConfirmBooking $confirm,
|
|
||||||
private PortalPrice $price,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, ?string> $guestData first_name and last_name are required, everything else optional
|
|
||||||
*
|
|
||||||
* @throws QuoteException
|
|
||||||
* @throws ReservationException
|
|
||||||
*/
|
|
||||||
public function handle(Property $property, Channel $channel, StayRequest $stay, array $guestData, string $process = self::CONFIRM, ?string $portalReference = null, ?int $portalTotal = null, ?string $notes = null, bool $guestConfirmed = false): Booking
|
|
||||||
{
|
|
||||||
if ($channel->property_id !== $property->id) {
|
|
||||||
throw new ReservationException('Der Kanal gehört nicht zu dieser Wohnung.');
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($process === self::CONTRACT && blank($guestData['email'] ?? null)) {
|
|
||||||
throw new ReservationException('Für den sofortigen Vertragsversand wird die E-Mail-Adresse des Gastes benötigt.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$booking = $this->create->handle($property, $stay, $guestData, source: 'portal', sendMails: false);
|
|
||||||
|
|
||||||
$changes = ['origin_channel_id' => $channel->id, 'portal_reference' => filled($portalReference) ? trim($portalReference) : null, 'internal_notes' => filled($notes) ? trim($notes) : $booking->internal_notes];
|
|
||||||
if ($guestConfirmed) {
|
|
||||||
$changes['guest_confirmed_at'] = now();
|
|
||||||
}
|
|
||||||
if ($portalTotal !== null) {
|
|
||||||
$changes += $this->price->columns($property, $stay, $portalTotal);
|
|
||||||
}
|
|
||||||
$booking->update($changes);
|
|
||||||
|
|
||||||
if ($process === self::RECORD) {
|
|
||||||
return $booking->refresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($process === self::CONTRACT) {
|
|
||||||
$this->confirm->handle($booking, notifyGuest: true);
|
|
||||||
} else {
|
|
||||||
DB::transaction(fn () => $this->confirm->bind($booking));
|
|
||||||
}
|
|
||||||
|
|
||||||
return $booking->refresh();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,344 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Documents\DocumentReleases;
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Enums\BookingTaskStatus;
|
||||||
|
use App\Enums\DataRequestMode;
|
||||||
|
use App\Enums\DocumentKind;
|
||||||
|
use App\Enums\FactSource;
|
||||||
|
use App\Enums\InquiryAnswer;
|
||||||
|
use App\Enums\IntakeKind;
|
||||||
|
use App\Mail\DataRequested;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingTask;
|
||||||
|
use App\Models\DataRequest;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Process\CaseRequirements;
|
||||||
|
use App\Process\FactContribution;
|
||||||
|
use App\Support\Settings;
|
||||||
|
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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The data request of v0.11 (S1, S4, CH-04, CH-15–CH-18): when the next step of a case lacks details, the guest is
|
||||||
|
* asked – automatically, prepared for the landlord's release, or by the landlord himself, as the case's settings say.
|
||||||
|
* At most one request runs per case. A partial answer leads to a targeted follow-up question, silence to reminders;
|
||||||
|
* both have their own limits and counters that are never reset. At the limit the landlord takes over.
|
||||||
|
*
|
||||||
|
* The request decides nothing about the case: answers go through the common fact intake, which asks the existing
|
||||||
|
* process to carry on. It never touches a hold or a deadline of the offer (CH-16/17, architecture test).
|
||||||
|
*/
|
||||||
|
class RequestCaseData
|
||||||
|
{
|
||||||
|
/** What the details are needed for. */
|
||||||
|
public const FOR_OFFER = 'offer';
|
||||||
|
|
||||||
|
public const FOR_WISH = 'wish_confirmation';
|
||||||
|
|
||||||
|
public const FOR_BOOKING = 'booking';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the case needs next and which details are missing for it, or null when nothing is to be asked.
|
||||||
|
*
|
||||||
|
* @return array{purpose: string, fields: list<string>}|null
|
||||||
|
*/
|
||||||
|
public static function needs(Booking $booking): ?array
|
||||||
|
{
|
||||||
|
$booking->loadMissing('guest');
|
||||||
|
if (in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true) || $booking->isInternal()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($booking->isBinding()) {
|
||||||
|
// A binding booking (also from a portal, E-036) stays binding; only administrative guest details are asked for.
|
||||||
|
if ($booking->departure->isPast()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$fields = array_values(array_filter(CaseRequirements::missing($booking), fn (string $field): bool => str_starts_with($field, 'guest.')));
|
||||||
|
|
||||||
|
return $fields === [] ? null : ['purpose' => self::FOR_BOOKING, 'fields' => $fields];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($booking->intake === IntakeKind::Booking || $booking->status !== BookingStatus::Reserved || $booking->offer_version > 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$purpose = match (true) {
|
||||||
|
$booking->process()->inquiryAnswer() === InquiryAnswer::Offer => self::FOR_OFFER,
|
||||||
|
$booking->wish_at !== null => self::FOR_WISH,
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
if ($purpose === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$fields = CaseRequirements::missing($booking, $purpose === self::FOR_WISH ? CaseRequirements::WISH_CONFIRMATION : CaseRequirements::OFFER);
|
||||||
|
|
||||||
|
return $fields === [] ? null : ['purpose' => $purpose, 'fields' => $fields];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the request for the next step if details are missing and none runs yet. Returns the running request.
|
||||||
|
*/
|
||||||
|
public function forNextStep(Booking $booking, ?DataRequestMode $mode = null): ?DataRequest
|
||||||
|
{
|
||||||
|
$needs = self::needs($booking);
|
||||||
|
// Without an e-mail address there is no way back to the guest: the case shows "enter the contact details".
|
||||||
|
if ($needs === null || ! CaseRequirements::isValid('guest.email', $booking->guest?->email)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$request = DB::transaction(function () use ($booking, $needs, $mode): DataRequest {
|
||||||
|
$booking->lockForTransition();
|
||||||
|
$running = $booking->openDataRequest();
|
||||||
|
if ($running !== null) {
|
||||||
|
return $running;
|
||||||
|
}
|
||||||
|
|
||||||
|
$mode ??= $booking->process()->dataRequestMode();
|
||||||
|
|
||||||
|
return $booking->dataRequests()->create([
|
||||||
|
'tenant_id' => $booking->tenant_id,
|
||||||
|
'status' => match (true) {
|
||||||
|
$mode === DataRequestMode::Manual => DataRequest::MANUAL,
|
||||||
|
$mode === DataRequestMode::Automatic && self::mayGoOutAutomatically() => DataRequest::OPEN,
|
||||||
|
default => DataRequest::DRAFT,
|
||||||
|
},
|
||||||
|
'mode' => $mode,
|
||||||
|
'purpose' => $needs['purpose'],
|
||||||
|
'fields' => $needs['fields'],
|
||||||
|
'last_message' => DataRequest::INITIAL,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
if ($request->wasRecentlyCreated) {
|
||||||
|
CaseLog::record($booking, 'data_request', match ($request->status) {
|
||||||
|
DataRequest::OPEN => 'Fehlende Angaben werden beim Gast angefragt',
|
||||||
|
DataRequest::DRAFT => 'Rückfrage nach fehlenden Angaben vorbereitet – wartet auf Ihre Freigabe',
|
||||||
|
default => 'Fehlende Angaben: bitte selbst beim Gast nachfragen (Textvorschlag im Vorgang)',
|
||||||
|
}, data: ['fields' => $request->fields], actor: CaseLog::SYSTEM);
|
||||||
|
|
||||||
|
if ($request->status === DataRequest::OPEN) {
|
||||||
|
$this->send($request, DataRequest::INITIAL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $request;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The landlord releases the prepared question (or asks now although the case is set to manual).
|
||||||
|
*/
|
||||||
|
public function approve(DataRequest $request): bool
|
||||||
|
{
|
||||||
|
if (! $request->isRunning()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (! CaseRequirements::isValid('guest.email', $request->booking->guest?->email)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$kind = $request->last_message === DataRequest::FOLLOWUP ? DataRequest::FOLLOWUP : DataRequest::INITIAL;
|
||||||
|
$request->update(['status' => DataRequest::OPEN]);
|
||||||
|
|
||||||
|
return $this->send($request, $kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends the question, follow-up or reminder. A failing mail is shown in the case; the landlord takes over.
|
||||||
|
*/
|
||||||
|
public function send(DataRequest $request, string $kind): bool
|
||||||
|
{
|
||||||
|
$booking = $request->booking()->with(['guest', 'property'])->firstOrFail();
|
||||||
|
$profile = $booking->process();
|
||||||
|
$needs = self::needs($booking);
|
||||||
|
if ($needs === null) {
|
||||||
|
$this->close($request, DataRequest::COMPLETED, 'alle Angaben da');
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$request->fields = $needs['fields'];
|
||||||
|
if ($kind === DataRequest::FOLLOWUP) {
|
||||||
|
$request->followups_sent++;
|
||||||
|
$request->link_version++;
|
||||||
|
}
|
||||||
|
if ($kind === DataRequest::REMINDER) {
|
||||||
|
$request->reminders_sent++;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new DataRequested($booking, $request, $kind, $this->url($request, $booking)));
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
Log::warning('Rückfrage nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||||
|
$request->forceFill(['status' => DataRequest::MANUAL])->save();
|
||||||
|
BookingTask::openOnce($booking, BookingTaskKind::GuestUnresponsive, 'r'.$request->id, ['due_on' => today(), 'note' => 'Die Rückfrage konnte nicht zugestellt werden – bitte die E-Mail-Adresse prüfen oder selbst nachfragen.']);
|
||||||
|
CaseLog::record($booking, 'data_request', 'Rückfrage konnte nicht zugestellt werden', actor: CaseLog::SYSTEM);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$request->forceFill([
|
||||||
|
'status' => DataRequest::OPEN,
|
||||||
|
'last_message' => $kind,
|
||||||
|
'last_sent_at' => now(),
|
||||||
|
'response_due_at' => now()->addHours($profile->reminderHours()),
|
||||||
|
'next_reminder_at' => now()->addHours($profile->reminderHours()),
|
||||||
|
])->save();
|
||||||
|
CaseLog::record($booking, 'data_request', match ($kind) {
|
||||||
|
DataRequest::FOLLOWUP => 'Gezielte Folgefrage an den Gast ('.$request->followups_sent.'.)',
|
||||||
|
DataRequest::REMINDER => 'Erinnerung an den Gast ('.$request->reminders_sent.'.)',
|
||||||
|
default => 'Rückfrage an den Gast gesendet',
|
||||||
|
}.': '.implode(', ', CaseRequirements::labels($request->fields)), actor: CaseLog::SYSTEM);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Details arrived (any source): the open reminder is cancelled; if everything is there the request ends, otherwise
|
||||||
|
* a targeted follow-up question follows within its limit (CH-15–17). The landlord's own entries never trigger a
|
||||||
|
* question to the guest.
|
||||||
|
*/
|
||||||
|
public function answered(Booking $booking, FactContribution $contribution, FactSource $source): void
|
||||||
|
{
|
||||||
|
$request = $booking->openDataRequest();
|
||||||
|
if ($request === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$needs = self::needs($booking->refresh());
|
||||||
|
if ($needs === null) {
|
||||||
|
$this->close($request, DataRequest::COMPLETED, 'alle Angaben da');
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($source->isAuthoritative() && $request->status === DataRequest::OPEN && $request->next_reminder_at === null && $request->followups_sent < $booking->process()->followupsMax()) {
|
||||||
|
// The landlord took over the guest's e-mail answer and something is still missing: a follow-up question is
|
||||||
|
// prepared for his release.
|
||||||
|
$request->forceFill(['status' => DataRequest::DRAFT, 'last_message' => DataRequest::FOLLOWUP, 'fields' => $needs['fields']])->save();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($source->isAuthoritative() || $request->status !== DataRequest::OPEN || (! $contribution->anyApplied() && ! $contribution->needsReview())) {
|
||||||
|
$request->update(['fields' => $needs['fields']]);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$request->forceFill(['answered_at' => now(), 'next_reminder_at' => null, 'fields' => $needs['fields']])->save();
|
||||||
|
|
||||||
|
if ($request->followups_sent >= $booking->process()->followupsMax()) {
|
||||||
|
$this->handOver($request, 'Antwort weiterhin unvollständig – die Grenze der Folgefragen ist erreicht.');
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($request->mode === DataRequestMode::Automatic && self::mayGoOutAutomatically()) {
|
||||||
|
$this->send($request, DataRequest::FOLLOWUP);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$request->forceFill(['status' => $request->mode === DataRequestMode::Manual ? DataRequest::MANUAL : DataRequest::DRAFT, 'last_message' => DataRequest::FOLLOWUP])->save();
|
||||||
|
CaseLog::record($booking, 'data_request', 'Antwort unvollständig – Folgefrage vorbereitet: '.implode(', ', CaseRequirements::labels($needs['fields'])), actor: CaseLog::SYSTEM);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A reply of the guest arrived (assigned by the inbox): the open reminder is cancelled (CH-17). What it says is
|
||||||
|
* taken over only through the extraction and the fact intake.
|
||||||
|
*/
|
||||||
|
public function replyReceived(Booking $booking): void
|
||||||
|
{
|
||||||
|
$request = $booking->openDataRequest();
|
||||||
|
if ($request?->status !== DataRequest::OPEN) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$request->forceFill(['answered_at' => now(), 'next_reminder_at' => null])->save();
|
||||||
|
CaseLog::record($booking, 'data_request', 'Antwort des Gastes per E-Mail – Erinnerungen ruhen', actor: CaseLog::SYSTEM);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Due reminders of every running request (scheduler). At the limit the landlord takes over; nothing changes any
|
||||||
|
* deadline of the case.
|
||||||
|
*/
|
||||||
|
public function remindDue(): int
|
||||||
|
{
|
||||||
|
$count = 0;
|
||||||
|
$due = DataRequest::query()->where('status', DataRequest::OPEN)->whereNotNull('next_reminder_at')->where('next_reminder_at', '<=', now())->with('booking')->get();
|
||||||
|
|
||||||
|
foreach ($due as $request) {
|
||||||
|
$booking = $request->booking;
|
||||||
|
if ($booking === null || self::needs($booking) === null) {
|
||||||
|
$this->close($request, $booking === null ? DataRequest::STOPPED : DataRequest::COMPLETED, $booking === null ? 'Vorgang entfernt' : 'nichts mehr offen');
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($request->reminders_sent >= $booking->process()->remindersMax()) {
|
||||||
|
$this->handOver($request, 'Der Gast hat auf die Rückfrage und '.$request->reminders_sent.' Erinnerung(en) nicht geantwortet.');
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$count += $this->send($request, DataRequest::REMINDER) ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ends the request (all details there, the case ended, or the landlord stopped it).
|
||||||
|
*/
|
||||||
|
public function close(DataRequest $request, string $status, string $reason): void
|
||||||
|
{
|
||||||
|
if (! $request->isRunning()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$request->forceFill(['status' => $status, 'closed_at' => now(), 'closed_reason' => $reason, 'next_reminder_at' => null])->save();
|
||||||
|
BookingTask::query()->where('booking_id', $request->booking_id)->where('kind', BookingTaskKind::GuestUnresponsive)->where('subject', 'r'.$request->id)->where('status', BookingTaskStatus::Open)
|
||||||
|
->get()->each(fn (BookingTask $task): bool => $task->forceFill(['status' => BookingTaskStatus::Done, 'completed_at' => now(), 'note' => trim($task->note.' · '.$reason)])->save());
|
||||||
|
if ($request->booking !== null) {
|
||||||
|
CaseLog::record($request->booking, 'data_request', 'Rückfrage beendet: '.$reason, actor: CaseLog::actor() ?? CaseLog::SYSTEM);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The guest's signed link to the form; it belongs to this request and its current version.
|
||||||
|
*/
|
||||||
|
public function url(DataRequest $request, ?Booking $booking = null): string
|
||||||
|
{
|
||||||
|
$booking ??= $request->booking;
|
||||||
|
$parameters = ['booking' => $booking, 'r' => $request->id, 'v' => $request->link_version];
|
||||||
|
$until = CarbonImmutable::now()->addDays($booking->process()->guestLinkValidDays());
|
||||||
|
|
||||||
|
return $booking->website()?->temporarySignedRoute('guest-data.show', $until, $parameters)
|
||||||
|
?? URL::temporarySignedRoute('guest-data.show', $until, $parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a question may go out without the landlord's click: its texts are released, or mails only reach the test
|
||||||
|
* recipient anyway (as for the automatic offer).
|
||||||
|
*/
|
||||||
|
public static function mayGoOutAutomatically(): bool
|
||||||
|
{
|
||||||
|
return DocumentReleases::isReleased(DocumentKind::DataRequest) || ! Settings::isLive();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function handOver(DataRequest $request, string $note): void
|
||||||
|
{
|
||||||
|
$request->forceFill(['status' => DataRequest::MANUAL, 'next_reminder_at' => null])->save();
|
||||||
|
BookingTask::openOnce($request->booking, BookingTaskKind::GuestUnresponsive, 'r'.$request->id, ['due_on' => today(), 'note' => $note]);
|
||||||
|
CaseLog::record($request->booking, 'data_request', 'Rückfrage an Sie übergeben: '.$note, actor: CaseLog::SYSTEM);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,8 +3,11 @@
|
|||||||
namespace App\Actions;
|
namespace App\Actions;
|
||||||
|
|
||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\Responsibility;
|
||||||
use App\Mail\ReviewRequest;
|
use App\Mail\ReviewRequest;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
|
use App\Process\OutwardSuspension;
|
||||||
|
use App\Process\ProcessPlan;
|
||||||
use Illuminate\Support\Facades\Mail;
|
use Illuminate\Support\Facades\Mail;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -25,7 +28,11 @@ public function handle(): int
|
|||||||
->whereDoesntHave('review')
|
->whereDoesntHave('review')
|
||||||
->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
|
->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
|
||||||
->with('guest')
|
->with('guest')
|
||||||
->get();
|
->get()
|
||||||
|
->filter(fn (Booking $booking): bool => $booking->process()->reviewRequestSender() === Responsibility::Landlord
|
||||||
|
// The step can be switched off per channel (Kanal › Ablauf); an open portal report holds it back (O4).
|
||||||
|
&& ProcessPlan::of($booking)->enabled('review.request')
|
||||||
|
&& OutwardSuspension::reason($booking) === null);
|
||||||
|
|
||||||
foreach ($bookings as $booking) {
|
foreach ($bookings as $booking) {
|
||||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReviewRequest($booking));
|
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReviewRequest($booking));
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
<?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).'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates the contract document and files it internally – without sending anything to the guest (delivery „internal“,
|
||||||
|
* docs/Prozessarchitektur/V2.1/02 §4). Same gate as the automatic dispatch: the composition must be clean.
|
||||||
|
*
|
||||||
|
* @return list<string> reasons why it was not created (empty: filed or already there)
|
||||||
|
*/
|
||||||
|
public function storeInternally(Booking $booking): array
|
||||||
|
{
|
||||||
|
if ($booking->contract_path !== null) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$composition = $this->compose($booking);
|
||||||
|
if (! $composition->canSendAutomatically()) {
|
||||||
|
return [...$composition->blockers(), ...array_map(fn (string $point): string => 'Bitte prüfen: '.$point, $composition->toConfirm())];
|
||||||
|
}
|
||||||
|
|
||||||
|
$lock = Cache::lock('booking-documents-'.$booking->id, 120);
|
||||||
|
if (! $lock->get()) {
|
||||||
|
return ['Die Unterlagen werden gerade bearbeitet.'];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$booking->refresh();
|
||||||
|
if (! $composition->termsFrozen && $composition->terms !== null) {
|
||||||
|
$booking->update(['offer_terms' => $composition->terms]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return CaseLog::context(fn (): bool => $this->confirm->deliver($booking, notifyGuest: false, kind: $composition->kind), actor: CaseLog::SYSTEM.' (automatisch)')
|
||||||
|
? [] : ['Das Vertragsdokument konnte nicht erstellt werden (siehe Postfach).'];
|
||||||
|
} finally {
|
||||||
|
$lock->release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Enums\BookingNoticeMode;
|
||||||
|
use App\Exceptions\ReservationException;
|
||||||
|
use App\Mail\BookingNotice;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Process\ChannelCapabilities;
|
||||||
|
use App\Process\PortalConfirmation;
|
||||||
|
use Illuminate\Support\Facades\Mail;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends the guest of a binding booking a short booking information (V2.1, docs/Prozessarchitektur/V2.1/02 §4) – separate
|
||||||
|
* from the contract documentation, which has its own step. Once only (the history entry `booking_notice` is the record).
|
||||||
|
* Where the landlord chose „unless the portal confirmed“, it is not sent when the portal informs the guest itself (confirmed
|
||||||
|
* capability of the channel) and its booking confirmation for this case is on record; the reason is kept in the history.
|
||||||
|
*/
|
||||||
|
class SendBookingNotice
|
||||||
|
{
|
||||||
|
public const EVENT = 'booking_notice';
|
||||||
|
|
||||||
|
public static function sent(Booking $booking): bool
|
||||||
|
{
|
||||||
|
return $booking->events()->where('type', self::EVENT)->where('summary', 'not like', 'Keine eigene%')->exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Why no own notice is needed, or null when it is.
|
||||||
|
*/
|
||||||
|
public static function suppression(Booking $booking): ?string
|
||||||
|
{
|
||||||
|
if ($booking->process()->bookingNotice() !== BookingNoticeMode::AutomaticUnlessPortalConfirmed) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$channel = $booking->processChannel();
|
||||||
|
if ($channel === null || app(ChannelCapabilities::class)->value($channel, ChannelCapabilities::MESSAGES_GUEST) !== true) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$evidence = PortalConfirmation::evidence($booking);
|
||||||
|
|
||||||
|
return $evidence === null ? null : 'Das Portal informiert den Gast selbst und hat die Buchung bestätigt ('.$evidence['label'].').';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws ReservationException
|
||||||
|
*/
|
||||||
|
public function handle(Booking $booking, bool $automatic = false): bool
|
||||||
|
{
|
||||||
|
$booking->loadMissing(['guest', 'property']);
|
||||||
|
if (! $booking->isBinding()) {
|
||||||
|
throw ReservationException::invalidTransition($booking->status->getLabel(), 'mit einer Buchungsinformation bedacht');
|
||||||
|
}
|
||||||
|
if (self::sent($booking)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (blank($booking->guest?->email)) {
|
||||||
|
throw new ReservationException('Vor dem Versand bitte die E-Mail-Adresse des Gastes ergänzen.');
|
||||||
|
}
|
||||||
|
if ($automatic && ($reason = self::suppression($booking)) !== null) {
|
||||||
|
if (! $booking->events()->where('type', self::EVENT)->exists()) {
|
||||||
|
CaseLog::record($booking, self::EVENT, 'Keine eigene Buchungsinformation nötig', reason: $reason, data: ['level' => 'stated_by_portal']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingNotice($booking));
|
||||||
|
CaseLog::record($booking, self::EVENT, 'Buchungsinformation an den Gast gesendet', actor: $automatic ? CaseLog::SYSTEM.' (automatisch)' : null);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,9 +5,11 @@
|
|||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
use App\Enums\BookingTaskKind;
|
use App\Enums\BookingTaskKind;
|
||||||
use App\Enums\BookingTaskStatus;
|
use App\Enums\BookingTaskStatus;
|
||||||
|
use App\Enums\Responsibility;
|
||||||
use App\Mail\ArrivalInformation;
|
use App\Mail\ArrivalInformation;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
use App\Models\BookingTask;
|
use App\Models\BookingTask;
|
||||||
|
use App\Process\OutwardSuspension;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\Mail;
|
use Illuminate\Support\Facades\Mail;
|
||||||
@@ -16,7 +18,8 @@
|
|||||||
* Daily booking workflow. Payments are never chased automatically: due payments become tasks for the landlord
|
* Daily booking workflow. Payments are never chased automatically: due payments become tasks for the landlord
|
||||||
* (BookingTask, once per booking and kind) who checks the payment and sends the reminder on a click
|
* (BookingTask, once per booking and kind) who checks the payment and sends the reminder on a click
|
||||||
* ({@see SendPaymentReminder}). Only the arrival information goes out by itself, once per booking, the configured
|
* ({@see SendPaymentReminder}). Only the arrival information goes out by itself, once per booking, the configured
|
||||||
* number of days before arrival. Completion after departure.
|
* number of days before arrival. Preparation of the stays and their closing after departure ({@see PrepareStays},
|
||||||
|
* {@see CloseStay}).
|
||||||
*/
|
*/
|
||||||
class SendBookingReminders
|
class SendBookingReminders
|
||||||
{
|
{
|
||||||
@@ -26,7 +29,7 @@ class SendBookingReminders
|
|||||||
private const ARRIVAL_INFO_MAX_DAYS_BEFORE = 14;
|
private const ARRIVAL_INFO_MAX_DAYS_BEFORE = 14;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int}
|
* @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int, prepared: int}
|
||||||
*/
|
*/
|
||||||
public function handle(): array
|
public function handle(): array
|
||||||
{
|
{
|
||||||
@@ -60,24 +63,26 @@ public function handle(): array
|
|||||||
->whereNull('arrival_info_sent_at')
|
->whereNull('arrival_info_sent_at')
|
||||||
->whereDate('arrival', '>=', $today)
|
->whereDate('arrival', '>=', $today)
|
||||||
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_MAX_DAYS_BEFORE)))
|
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_MAX_DAYS_BEFORE)))
|
||||||
->filter(fn (Booking $booking): bool => $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->property->arrival_info_days_before)));
|
->filter(fn (Booking $booking): bool => $booking->process()->arrivalInfoSender() === Responsibility::Landlord
|
||||||
|
&& $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->process()->arrivalInfoDaysBefore()))
|
||||||
|
// Decision O4: an open portal report of a cancellation or change holds the message back until clarified.
|
||||||
|
&& OutwardSuspension::reason($booking) === null);
|
||||||
foreach ($arrivals as $booking) {
|
foreach ($arrivals as $booking) {
|
||||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking));
|
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking));
|
||||||
$booking->update(['arrival_info_sent_at' => now()]);
|
$booking->update(['arrival_info_sent_at' => now()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$completed = Booking::query()
|
// Package 9: prepare the coming stays, close the stays whose departure has passed (open money stays as follow-up).
|
||||||
->where('status', BookingStatus::Paid)
|
$prepared = app(PrepareStays::class)->handle();
|
||||||
->whereDate('departure', '<', $today)
|
$completed = app(CloseStay::class)->due();
|
||||||
->get();
|
|
||||||
$completed->each->update(['status' => BookingStatus::Completed]);
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'deposit_overdue' => $depositTasks,
|
'deposit_overdue' => $depositTasks,
|
||||||
'balance_request' => $requestTasks,
|
'balance_request' => $requestTasks,
|
||||||
'balance_overdue' => $overdueTasks,
|
'balance_overdue' => $overdueTasks,
|
||||||
'arrival_info' => $arrivals->count(),
|
'arrival_info' => $arrivals->count(),
|
||||||
'completed' => $completed->count(),
|
'completed' => $completed,
|
||||||
|
'prepared' => $prepared['arrival_details'] + $prepared['stay_tasks'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,186 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Availability\AvailabilityChecker;
|
||||||
|
use App\Documents\DocumentComposer;
|
||||||
|
use App\Documents\OfferTerms;
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Enums\BookingTaskStatus;
|
||||||
|
use App\Enums\DocumentKind;
|
||||||
|
use App\Enums\InboxMessageKind;
|
||||||
|
use App\Exceptions\ReservationException;
|
||||||
|
use App\Filament\Resources\Bookings\BookingResource;
|
||||||
|
use App\Mail\InformationSent;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingTask;
|
||||||
|
use App\Pricing\QuoteException;
|
||||||
|
use App\Pricing\StayRequest;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Support\Inbox;
|
||||||
|
use App\Support\Money;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Illuminate\Support\Facades\Mail;
|
||||||
|
use Illuminate\Support\Facades\URL;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Package 7 (E-026, P02 "Haltefrist = 0"): answers a request that reserves nothing with an information "unter Vorbehalt" –
|
||||||
|
* price and availability as checked now, no reservation and no acceptance link that could conclude a contract. The guest
|
||||||
|
* gets a signed link to ask for the booking ({@see SubmitBookingWish}); everything is checked again then.
|
||||||
|
*
|
||||||
|
* Sending again replaces the previous information: older links stop working and a booking wish made on them is void.
|
||||||
|
*/
|
||||||
|
class SendInformation
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private SendOffer $offer,
|
||||||
|
private AvailabilityChecker $availability,
|
||||||
|
private Inbox $inbox,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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
|
||||||
|
*/
|
||||||
|
public function handle(Booking $booking, array $changes = [], bool $sendMail = true): Booking
|
||||||
|
{
|
||||||
|
if ($sendMail && blank($booking->guest?->email)) {
|
||||||
|
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$toConfirm = app(DocumentComposer::class)->compose($booking, DocumentKind::Information, $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();
|
||||||
|
|
||||||
|
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::Expired], true) || $booking->isHoldActive()) {
|
||||||
|
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Auskunft beantwortet');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($changes['expected_version']) && $booking->information_version !== (int) $changes['expected_version']) {
|
||||||
|
throw new ReservationException('Inzwischen wurde schon eine Auskunft gesendet (Version '.$booking->information_version.'). Es wurde nichts erneut gesendet.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
|
||||||
|
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
|
||||||
|
|
||||||
|
if (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) {
|
||||||
|
throw ReservationException::notAvailable();
|
||||||
|
}
|
||||||
|
|
||||||
|
$promoCode = array_key_exists('promo_code', $changes) ? (filled($changes['promo_code']) ? trim((string) $changes['promo_code']) : null) : $booking->promo_code;
|
||||||
|
$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->offer->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']));
|
||||||
|
}
|
||||||
|
|
||||||
|
$validUntil = filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours());
|
||||||
|
$booking->update([
|
||||||
|
'status' => BookingStatus::Reserved,
|
||||||
|
'hold_expires_at' => null,
|
||||||
|
'arrival' => $arrival->toDateString(),
|
||||||
|
'departure' => $departure->toDateString(),
|
||||||
|
'guests' => $stay->guests,
|
||||||
|
'promo_code' => $quote->promoCodeApplied ? $promoCode : null,
|
||||||
|
'price_adjustment' => $adjustment !== 0 ? $adjustment : null,
|
||||||
|
'price_adjustment_label' => $adjustment !== 0 ? $adjustmentLabel : null,
|
||||||
|
'quote' => $quote->toArray(),
|
||||||
|
'total' => $quote->total(),
|
||||||
|
'deposit' => $quote->deposit(),
|
||||||
|
'balance_due_on' => $quote->balanceDueOn->toDateString(),
|
||||||
|
'information_version' => $booking->information_version + 1,
|
||||||
|
'information_sent_at' => now(),
|
||||||
|
'information_valid_until' => $validUntil,
|
||||||
|
'offer_message' => $changes['offer_message'] ?? null,
|
||||||
|
'offer_terms' => OfferTerms::capture(OfferTerms::templateFor($booking, $changes['contract_template_id'] ?? null), $booking, array_key_exists('annex_ids', $changes) && is_array($changes['annex_ids']) ? array_map('intval', $changes['annex_ids']) : null),
|
||||||
|
// A wish on an older information is void; the guest asks again on the new one.
|
||||||
|
'wish_at' => null,
|
||||||
|
'wish' => null,
|
||||||
|
]);
|
||||||
|
$booking->refresh();
|
||||||
|
$booking->update(['information' => [
|
||||||
|
'version' => $booking->information_version,
|
||||||
|
'sent_at' => $booking->information_sent_at?->toIso8601String(),
|
||||||
|
'valid_until' => $validUntil->toIso8601String(),
|
||||||
|
'total' => $booking->total,
|
||||||
|
'quote_sha256' => self::quoteHash($booking),
|
||||||
|
'terms_sha256' => hash('sha256', json_encode($booking->offer_terms['texts'] ?? [])),
|
||||||
|
]]);
|
||||||
|
|
||||||
|
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::BookingWish)->where('status', BookingTaskStatus::Open)
|
||||||
|
->update(['status' => BookingTaskStatus::Dismissed, 'note' => 'Durch eine neue Auskunft ersetzt.', 'completed_at' => now(), 'completed_by' => CaseLog::actor()]);
|
||||||
|
});
|
||||||
|
|
||||||
|
$booking->refresh();
|
||||||
|
CaseLog::record($booking, 'document', 'Auskunft unter Vorbehalt Version '.$booking->information_version.' erstellt (Preis '.Money::format((int) $booking->total).', ohne Reservierung)', data: array_filter([
|
||||||
|
'kind' => DocumentKind::Information->value,
|
||||||
|
'template' => $booking->offer_terms['template'] ?? null,
|
||||||
|
'information' => $booking->information,
|
||||||
|
'confirmed' => $toConfirm,
|
||||||
|
]));
|
||||||
|
|
||||||
|
if ($sendMail) {
|
||||||
|
$this->deliver($booking);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $booking;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends the information mail; a failing mail server keeps the saved information and is reported in the inbox.
|
||||||
|
*
|
||||||
|
* @throws ReservationException
|
||||||
|
*/
|
||||||
|
public function deliver(Booking $booking): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new InformationSent($booking, $this->informationUrl($booking)));
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
Log::warning('Auskunft nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||||
|
$this->inbox->post(
|
||||||
|
InboxMessageKind::OfferMailFailed,
|
||||||
|
'booking-'.$booking->id.':i'.$booking->information_version,
|
||||||
|
'Auskunft '.$booking->reference.' nicht zugestellt',
|
||||||
|
'Die Auskunft ist gespeichert, aber die E-Mail konnte nicht versendet werden. Auf der Vorgangsseite kann der Link kopiert und dem Gast anders übermittelt werden.',
|
||||||
|
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
|
||||||
|
propertyId: $booking->property_id,
|
||||||
|
);
|
||||||
|
|
||||||
|
throw new ReservationException('Die Auskunft wurde gespeichert, aber die E-Mail konnte nicht versendet werden.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The guest's link to the information page; valid while the information is valid and only for this version.
|
||||||
|
*/
|
||||||
|
public function informationUrl(Booking $booking): string
|
||||||
|
{
|
||||||
|
$parameters = ['booking' => $booking, 'v' => $booking->information_version];
|
||||||
|
$until = $booking->information_valid_until ?? now()->addDay();
|
||||||
|
|
||||||
|
return $booking->website()?->temporarySignedRoute('information.show', $until, $parameters)
|
||||||
|
?? URL::temporarySignedRoute('information.show', $until, $parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fingerprint of the price lines the guest was told.
|
||||||
|
*/
|
||||||
|
public static function quoteHash(Booking $booking): string
|
||||||
|
{
|
||||||
|
return hash('sha256', json_encode([$booking->quote['lines'] ?? [], $booking->total, $booking->arrival?->toDateString(), $booking->departure?->toDateString(), $booking->guests]));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,20 +3,25 @@
|
|||||||
namespace App\Actions;
|
namespace App\Actions;
|
||||||
|
|
||||||
use App\Availability\AvailabilityChecker;
|
use App\Availability\AvailabilityChecker;
|
||||||
|
use App\Documents\DocumentComposer;
|
||||||
use App\Documents\OfferTerms;
|
use App\Documents\OfferTerms;
|
||||||
use App\Documents\RentalContract;
|
use App\Documents\RentalContract;
|
||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\DocumentKind;
|
||||||
use App\Enums\InboxMessageKind;
|
use App\Enums\InboxMessageKind;
|
||||||
use App\Enums\QuoteLineType;
|
use App\Enums\QuoteLineType;
|
||||||
use App\Exceptions\ReservationException;
|
use App\Exceptions\ReservationException;
|
||||||
use App\Filament\Resources\Bookings\BookingResource;
|
use App\Filament\Resources\Bookings\BookingResource;
|
||||||
use App\Mail\OfferMade;
|
use App\Mail\OfferMade;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
|
use App\Pricing\CasePricing;
|
||||||
use App\Pricing\PriceCalculator;
|
use App\Pricing\PriceCalculator;
|
||||||
use App\Pricing\PriceQuote;
|
use App\Pricing\PriceQuote;
|
||||||
use App\Pricing\QuoteException;
|
use App\Pricing\QuoteException;
|
||||||
use App\Pricing\QuoteLine;
|
use App\Pricing\QuoteLine;
|
||||||
use App\Pricing\StayRequest;
|
use App\Pricing\StayRequest;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Process\CaseRequirements;
|
||||||
use App\Support\Inbox;
|
use App\Support\Inbox;
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Illuminate\Support\Arr;
|
use Illuminate\Support\Arr;
|
||||||
@@ -42,7 +47,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 QuoteException
|
||||||
* @throws ReservationException
|
* @throws ReservationException
|
||||||
@@ -57,6 +67,16 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
|
|||||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet');
|
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// G2a (v0.11): never an own binding offer without the required details – not even confirmed by hand.
|
||||||
|
if (($missing = CaseRequirements::blocker($booking->loadMissing('guest'), CaseRequirements::OFFER)) !== null) {
|
||||||
|
throw new ReservationException($missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
$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 {
|
DB::transaction(function () use ($booking, $changes): void {
|
||||||
$booking->lockForTransition();
|
$booking->lockForTransition();
|
||||||
|
|
||||||
@@ -64,6 +84,10 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
|
|||||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet');
|
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);
|
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
|
||||||
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
|
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
|
||||||
|
|
||||||
@@ -75,7 +99,7 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
|
|||||||
$stay = new StayRequest($arrival, $departure, (int) ($changes['guests'] ?? $booking->guests), $booking->extras ?? [], $promoCode);
|
$stay = new StayRequest($arrival, $departure, (int) ($changes['guests'] ?? $booking->guests), $booking->extras ?? [], $promoCode);
|
||||||
$adjustment = (int) ($changes['price_adjustment'] ?? 0);
|
$adjustment = (int) ($changes['price_adjustment'] ?? 0);
|
||||||
$adjustmentLabel = trim((string) ($changes['price_adjustment_label'] ?? '')) ?: ($adjustment < 0 ? 'Nachlass' : 'Zuschlag');
|
$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)) {
|
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']));
|
$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']));
|
||||||
@@ -93,7 +117,8 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
|
|||||||
'total' => $quote->total(),
|
'total' => $quote->total(),
|
||||||
'deposit' => $quote->deposit(),
|
'deposit' => $quote->deposit(),
|
||||||
'balance_due_on' => $quote->balanceDueOn->toDateString(),
|
'balance_due_on' => $quote->balanceDueOn->toDateString(),
|
||||||
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->property->hold_hours),
|
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()),
|
||||||
|
'hold_purpose' => Booking::HOLD_OFFER,
|
||||||
'offer_version' => $booking->offer_version + 1,
|
'offer_version' => $booking->offer_version + 1,
|
||||||
'offer_sent_at' => now(),
|
'offer_sent_at' => now(),
|
||||||
'offer_message' => $changes['offer_message'] ?? null,
|
'offer_message' => $changes['offer_message'] ?? null,
|
||||||
@@ -105,6 +130,14 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
|
|||||||
|
|
||||||
$booking->refresh();
|
$booking->refresh();
|
||||||
$this->contract->generate($booking, draft: true);
|
$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) {
|
if ($sendMail) {
|
||||||
$this->deliver($booking);
|
$this->deliver($booking);
|
||||||
@@ -155,9 +188,10 @@ public function offerUrl(Booking $booking): string
|
|||||||
*
|
*
|
||||||
* @throws QuoteException
|
* @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);
|
// Extension point BeforePriceFixing (Architektur V2): PriceCalculator plus the lines of contributing modules.
|
||||||
|
$quote = app(CasePricing::class)->quote($booking, $stay);
|
||||||
if ($adjustment === 0) {
|
if ($adjustment === 0) {
|
||||||
return $quote;
|
return $quote;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
use App\Exceptions\ReservationException;
|
use App\Exceptions\ReservationException;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
use App\Models\BookingTask;
|
use App\Models\BookingTask;
|
||||||
|
use App\Process\CaseLog;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -33,6 +34,10 @@ public function handle(Booking $booking, BookingStatus $status, string $reason,
|
|||||||
throw new ReservationException('Auf diesen Status kann nicht von Hand gewechselt werden. Stornieren und Ablehnen haben eigene Aktionen.');
|
throw new ReservationException('Auf diesen Status kann nicht von Hand gewechselt werden. Stornieren und Ablehnen haben eigene Aktionen.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($status === BookingStatus::Reserved && in_array($booking->status, BookingStatus::occupying(), true)) {
|
||||||
|
throw new ReservationException('Eine verbindliche Buchung kann nicht wieder zur Anfrage gemacht werden. Soll sie enden, bitte „Beenden“ wählen – dann wird sie ordentlich storniert.');
|
||||||
|
}
|
||||||
|
|
||||||
if (blank(trim($reason))) {
|
if (blank(trim($reason))) {
|
||||||
throw new ReservationException('Bitte einen Grund für die Statusänderung angeben.');
|
throw new ReservationException('Bitte einen Grund für die Statusänderung angeben.');
|
||||||
}
|
}
|
||||||
@@ -44,6 +49,9 @@ public function handle(Booking $booking, BookingStatus $status, string $reason,
|
|||||||
if ($from === $status) {
|
if ($from === $status) {
|
||||||
throw new ReservationException('Die Buchung hat diesen Status bereits.');
|
throw new ReservationException('Die Buchung hat diesen Status bereits.');
|
||||||
}
|
}
|
||||||
|
if ($status === BookingStatus::Reserved && in_array($from, BookingStatus::occupying(), true)) {
|
||||||
|
throw new ReservationException('Eine verbindliche Buchung kann nicht wieder zur Anfrage gemacht werden.');
|
||||||
|
}
|
||||||
|
|
||||||
$becomesBinding = in_array($status, BookingStatus::occupying(), true) && ! in_array($from, BookingStatus::occupying(), true);
|
$becomesBinding = in_array($status, BookingStatus::occupying(), true) && ! in_array($from, BookingStatus::occupying(), true);
|
||||||
if ($becomesBinding && ! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
|
if ($becomesBinding && ! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
|
||||||
@@ -59,7 +67,7 @@ public function handle(Booking $booking, BookingStatus $status, string $reason,
|
|||||||
}
|
}
|
||||||
|
|
||||||
$line = now()->format('d.m.Y H:i').' '.$by.': Status von „'.$from->getLabel().'“ auf „'.$status->getLabel().'“ gesetzt – '.trim($reason);
|
$line = now()->format('d.m.Y H:i').' '.$by.': Status von „'.$from->getLabel().'“ auf „'.$status->getLabel().'“ gesetzt – '.trim($reason);
|
||||||
$booking->update($changes + ['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n" : '').$line)]);
|
CaseLog::context(fn () => $booking->update($changes + ['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n" : '').$line)]), actor: $by, reason: 'Von Hand gesetzt: '.trim($reason));
|
||||||
|
|
||||||
// A booking taken back into the process no longer needs the cancellation follow-up.
|
// A booking taken back into the process no longer needs the cancellation follow-up.
|
||||||
if ($becomesBinding) {
|
if ($becomesBinding) {
|
||||||
|
|||||||
@@ -0,0 +1,261 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Availability\AvailabilityChecker;
|
||||||
|
use App\Availability\CalendarClearance;
|
||||||
|
use App\Documents\DocumentComposer;
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Enums\DocumentKind;
|
||||||
|
use App\Enums\InboxMessageKind;
|
||||||
|
use App\Enums\ProcessingMode;
|
||||||
|
use App\Exceptions\ReservationException;
|
||||||
|
use App\Filament\Resources\Bookings\BookingResource;
|
||||||
|
use App\Mail\BookingWishAnswered;
|
||||||
|
use App\Mail\BookingWishNotice;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingTask;
|
||||||
|
use App\Pricing\QuoteException;
|
||||||
|
use App\Pricing\StayRequest;
|
||||||
|
use App\Process\CaseAutomation;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Process\CaseRequirements;
|
||||||
|
use App\Process\ProcessRunner;
|
||||||
|
use App\Support\Inbox;
|
||||||
|
use App\Support\Money;
|
||||||
|
use App\Support\Settings;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Illuminate\Support\Facades\Mail;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Package 7 (E-026, E-030): the guest asks for the booking from an information "unter Vorbehalt". Everything is checked
|
||||||
|
* again in one locked step – the whole stay still free, the imported portal calendars current, the price the guest was
|
||||||
|
* told still the price of today, the data for the booking complete. Then the effective processing decides:
|
||||||
|
* automatically the booking is confirmed at once (only when nothing at all stands in the way), otherwise the landlord
|
||||||
|
* gets the task "Buchungswunsch bestätigen?". When the dates were given away meanwhile, no booking comes about; the
|
||||||
|
* guest gets a friendly answer and the landlord a note.
|
||||||
|
*
|
||||||
|
* Asking again for the same information is harmless (no second booking, no second mail); a link of an older information
|
||||||
|
* no longer works.
|
||||||
|
*/
|
||||||
|
class SubmitBookingWish
|
||||||
|
{
|
||||||
|
public const CONFIRMED = 'confirmed';
|
||||||
|
|
||||||
|
public const PENDING = 'pending';
|
||||||
|
|
||||||
|
public const UNAVAILABLE = 'unavailable';
|
||||||
|
|
||||||
|
public const ALREADY = 'already';
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private SendOffer $offer,
|
||||||
|
private AvailabilityChecker $availability,
|
||||||
|
private CalendarClearance $clearance,
|
||||||
|
private ConfirmBooking $confirm,
|
||||||
|
private Inbox $inbox,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string one of the outcome constants
|
||||||
|
*
|
||||||
|
* @throws ReservationException when the link is outdated, expired or the request is no longer open
|
||||||
|
*/
|
||||||
|
public function handle(Booking $booking, int $version, ?string $ip = null): string
|
||||||
|
{
|
||||||
|
$booking->loadMissing(['guest', 'property']);
|
||||||
|
if ($this->alreadyAsked($booking, $version)) {
|
||||||
|
return self::ALREADY;
|
||||||
|
}
|
||||||
|
$this->ensureCurrent($booking, $version);
|
||||||
|
|
||||||
|
// Network access (calendar imports) stays outside the transaction.
|
||||||
|
rescue(fn () => $this->clearance->refresh($booking->property), report: false);
|
||||||
|
$stale = $this->clearance->staleImports($booking->property)->pluck('name')->all();
|
||||||
|
|
||||||
|
$outcome = DB::transaction(function () use ($booking, $version, $ip, $stale): string {
|
||||||
|
$booking->lockForTransition();
|
||||||
|
|
||||||
|
if ($this->alreadyAsked($booking, $version)) {
|
||||||
|
return self::ALREADY;
|
||||||
|
}
|
||||||
|
$this->ensureCurrent($booking, $version);
|
||||||
|
|
||||||
|
$record = [
|
||||||
|
'information_version' => $version,
|
||||||
|
'at' => now()->toIso8601String(),
|
||||||
|
'ip_hash' => $ip !== null ? hash('sha256', $ip.config('app.key')) : null,
|
||||||
|
'total_told' => $booking->information['total'] ?? $booking->total,
|
||||||
|
'terms_sha256' => $booking->information['terms_sha256'] ?? null,
|
||||||
|
'via' => 'information_link',
|
||||||
|
];
|
||||||
|
|
||||||
|
if (! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
|
||||||
|
$booking->update([
|
||||||
|
'wish_at' => now(),
|
||||||
|
'wish' => [...$record, 'outcome' => self::UNAVAILABLE, 'findings' => ['Der Zeitraum ist inzwischen vergeben.']],
|
||||||
|
'status' => BookingStatus::Declined,
|
||||||
|
'declined_by' => 'us',
|
||||||
|
]);
|
||||||
|
|
||||||
|
return self::UNAVAILABLE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$findings = $this->findings($booking, $stale);
|
||||||
|
$automatic = $booking->processingMode() === ProcessingMode::Automatic;
|
||||||
|
$booking->update([
|
||||||
|
'wish_at' => now(),
|
||||||
|
'wish' => [...$record, 'total_now' => $findings['total_now'], 'findings' => $findings['findings'], 'outcome' => $automatic && $findings['findings'] === [] ? self::CONFIRMED : self::PENDING],
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($automatic && $findings['findings'] === []) {
|
||||||
|
$this->confirm->bind($booking);
|
||||||
|
$booking->update([
|
||||||
|
'accepted_at' => now(),
|
||||||
|
'acceptance' => [
|
||||||
|
'via' => 'booking_wish',
|
||||||
|
'information_version' => $version,
|
||||||
|
'wish_at' => $booking->wish_at?->toIso8601String(),
|
||||||
|
'total' => $booking->total,
|
||||||
|
'quote_sha256' => SendInformation::quoteHash($booking),
|
||||||
|
'terms_sha256' => $record['terms_sha256'],
|
||||||
|
'confirmed_by' => 'automatisch nach erneuter Prüfung',
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
return self::CONFIRMED;
|
||||||
|
}
|
||||||
|
|
||||||
|
BookingTask::openOnce($booking, BookingTaskKind::BookingWish, 'v'.$version, [
|
||||||
|
'due_on' => today(),
|
||||||
|
'note' => $findings['findings'] === [] ? 'Zeitraum frei, Preis unverändert.' : implode(' ', $findings['findings']),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return self::PENDING;
|
||||||
|
});
|
||||||
|
|
||||||
|
$booking->refresh();
|
||||||
|
CaseLog::record($booking, 'wish', match ($outcome) {
|
||||||
|
self::CONFIRMED => 'Buchungswunsch des Gastes – automatisch geprüft und verbindlich bestätigt',
|
||||||
|
self::PENDING => 'Buchungswunsch des Gastes eingegangen – wartet auf Ihre Bestätigung',
|
||||||
|
self::UNAVAILABLE => 'Buchungswunsch des Gastes – Zeitraum inzwischen vergeben, keine Buchung',
|
||||||
|
default => 'Buchungswunsch wiederholt (ohne Wirkung)',
|
||||||
|
}, data: $outcome === self::ALREADY ? [] : ['wish' => $booking->wish], actor: CaseLog::GUEST);
|
||||||
|
|
||||||
|
$this->notify($booking, $outcome);
|
||||||
|
|
||||||
|
// v0.11 (B3): the binding confirmation needs every detail – ask the guest for what is missing.
|
||||||
|
if ($outcome === self::PENDING) {
|
||||||
|
app(ProcessRunner::class)->advance($booking->fresh(), 'wish');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $outcome;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks that the page shows the form for: the information is the current one, still valid and the request open.
|
||||||
|
*
|
||||||
|
* @throws ReservationException
|
||||||
|
*/
|
||||||
|
public function ensureCurrent(Booking $booking, int $version): void
|
||||||
|
{
|
||||||
|
if ($booking->information_version === 0 || $version !== $booking->information_version) {
|
||||||
|
throw new ReservationException('Diese Auskunft ist nicht mehr aktuell – wir haben Ihnen inzwischen eine neuere gesendet. Bitte verwenden Sie den Link aus der neuesten E-Mail.');
|
||||||
|
}
|
||||||
|
if ($booking->wish_at !== null) {
|
||||||
|
throw new ReservationException('Zu dieser Auskunft liegt Ihr Buchungswunsch bereits vor.');
|
||||||
|
}
|
||||||
|
if ($booking->status !== BookingStatus::Reserved) {
|
||||||
|
throw new ReservationException(in_array($booking->status, BookingStatus::occupying(), true)
|
||||||
|
? 'Ihre Buchung ist bereits verbindlich bestätigt – Sie müssen nichts weiter tun.'
|
||||||
|
: 'Diese Anfrage ist abgeschlossen. Gern können Sie über unsere Webseite neu anfragen.');
|
||||||
|
}
|
||||||
|
if (! $booking->information_valid_until?->isFuture()) {
|
||||||
|
throw new ReservationException('Diese Auskunft ist abgelaufen. Gern können Sie über unsere Webseite neu anfragen; wir prüfen dann Preis und Verfügbarkeit erneut.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Everything that keeps the wish from being confirmed automatically, and the price of today.
|
||||||
|
*
|
||||||
|
* @param list<string> $stale names of portals whose calendar is not current
|
||||||
|
* @return array{findings: list<string>, total_now: ?int}
|
||||||
|
*/
|
||||||
|
public function findings(Booking $booking, array $stale = []): array
|
||||||
|
{
|
||||||
|
$findings = [];
|
||||||
|
$totalNow = null;
|
||||||
|
try {
|
||||||
|
$label = (string) ($booking->price_adjustment_label ?: 'Zuschlag');
|
||||||
|
$quote = $this->offer->quoteFor($booking, new StayRequest($booking->arrival, $booking->departure, $booking->guests, $booking->extras ?? [], $booking->promo_code), (int) $booking->price_adjustment, $label);
|
||||||
|
$totalNow = $quote->total();
|
||||||
|
$told = (int) ($booking->information['total'] ?? $booking->total);
|
||||||
|
if ($totalNow !== $told) {
|
||||||
|
$findings[] = 'Der Preis hat sich seit der Auskunft geändert: damals '.Money::format($told).', heute '.Money::format($totalNow).'.';
|
||||||
|
}
|
||||||
|
} catch (QuoteException $exception) {
|
||||||
|
$findings[] = 'Der Preis lässt sich heute nicht berechnen: '.$exception->getMessage();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($stale !== []) {
|
||||||
|
$findings[] = 'Der Kalenderstand von '.implode(', ', $stale).' ist nicht aktuell.';
|
||||||
|
}
|
||||||
|
|
||||||
|
$findings = [...$findings, ...app(CaseAutomation::class)->documentBlockers($booking)];
|
||||||
|
if (($missing = CaseRequirements::blocker($booking, CaseRequirements::WISH_CONFIRMATION)) !== null) {
|
||||||
|
$findings[] = $missing;
|
||||||
|
}
|
||||||
|
if (! app(AutoOffer::class)->contractTextsReleased()) {
|
||||||
|
$findings[] = 'Mietbedingungen, Stornobedingungen oder Bankverbindung sind noch nicht vom Betreiber freigegeben (leer oder Mustertext).';
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the confirmation with the contract would need to be confirmed by the landlord (unreleased texts, gaps).
|
||||||
|
foreach (app(DocumentComposer::class)->compose($booking, DocumentKind::Confirmation)->toConfirm() as $point) {
|
||||||
|
$findings[] = $point;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['findings' => array_values(array_unique($findings)), 'total_now' => $totalNow];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function alreadyAsked(Booking $booking, int $version): bool
|
||||||
|
{
|
||||||
|
return $booking->wish_at !== null && ($booking->wish['information_version'] ?? null) === $version;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mails after the commit; none of them can undo what was decided.
|
||||||
|
*/
|
||||||
|
private function notify(Booking $booking, string $outcome): void
|
||||||
|
{
|
||||||
|
if ($outcome === self::ALREADY) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($outcome === self::CONFIRMED) {
|
||||||
|
$this->confirm->deliver($booking);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if ($outcome !== self::CONFIRMED && filled($booking->guest?->email)) {
|
||||||
|
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingWishAnswered($booking, $outcome));
|
||||||
|
}
|
||||||
|
Mail::to(Settings::notificationRecipients())->send(new BookingWishNotice($booking, $outcome));
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
Log::warning('Mail zum Buchungswunsch nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($outcome === self::UNAVAILABLE) {
|
||||||
|
$this->inbox->post(
|
||||||
|
InboxMessageKind::OfferRejected,
|
||||||
|
'wish-'.$booking->id.':i'.$booking->information_version,
|
||||||
|
'Buchungswunsch '.$booking->reference.': Zeitraum inzwischen vergeben',
|
||||||
|
'Der Gast hat aus der Auskunft die Buchung angefragt, aber der Zeitraum ist inzwischen belegt. Es ist keine Buchung entstanden; der Gast hat eine freundliche Absage erhalten.',
|
||||||
|
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
|
||||||
|
propertyId: $booking->property_id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@
|
|||||||
use App\Channels\ChannelSyncException;
|
use App\Channels\ChannelSyncException;
|
||||||
use App\Channels\ConflictDetector;
|
use App\Channels\ConflictDetector;
|
||||||
use App\Channels\ExternalPeriod;
|
use App\Channels\ExternalPeriod;
|
||||||
|
use App\Channels\Intake\PortalIntake;
|
||||||
use App\Enums\ChannelEchoBehavior;
|
use App\Enums\ChannelEchoBehavior;
|
||||||
use App\Models\BlockedPeriod;
|
use App\Models\BlockedPeriod;
|
||||||
use App\Models\Booking;
|
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();
|
'alerted_at' => null, 'last_import_events' => count($periods), 'sync_warnings' => $warnings])->save();
|
||||||
});
|
});
|
||||||
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
|
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,
|
return $channel->syncLogs()->create(['successful' => true, 'events' => count($periods), ...$counts,
|
||||||
'conflicts' => count($conflicts), 'warnings' => $warnings,
|
'conflicts' => count($conflicts), 'warnings' => $warnings,
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
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;
|
||||||
|
use App\Models\Channel;
|
||||||
|
use App\Models\Guest;
|
||||||
|
use App\Models\Property;
|
||||||
|
use App\Pricing\PortalPrice;
|
||||||
|
use App\Process\ProcessRunner;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Takes over a booking that a portal already made binding (case types A3–A5): one case with the portal as origin
|
||||||
|
* channel (owner), its reference and the facts the portal delivered – nothing more. There is no offer and no second
|
||||||
|
* acceptance; the agreed portal price is taken over as it is; guest, number of guests and price may be unknown and
|
||||||
|
* stay unknown until somebody enters them. The case is binding at once and occupies the dates.
|
||||||
|
*
|
||||||
|
* Used for the manual entry ("Buchung von einem Portal") and for a reservation found in a portal calendar – then the
|
||||||
|
* calendar entry stays as the portal's mirror of the case.
|
||||||
|
*/
|
||||||
|
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, processing_mode?: ?ProcessingMode} $facts
|
||||||
|
*
|
||||||
|
* @throws ReservationException
|
||||||
|
*/
|
||||||
|
public function handle(Property $property, Channel $channel, CarbonImmutable $arrival, CarbonImmutable $departure, array $facts = [], ?BlockedPeriod $evidence = null): Booking
|
||||||
|
{
|
||||||
|
if ($channel->property_id !== $property->id) {
|
||||||
|
throw new ReservationException('Der Kanal gehört nicht zu dieser Wohnung.');
|
||||||
|
}
|
||||||
|
if ($departure->lessThanOrEqualTo($arrival)) {
|
||||||
|
throw new ReservationException('Die Abreise muss nach der Anreise liegen.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$booking = DB::transaction(function () use ($property, $channel, $arrival, $departure, $facts, $evidence): Booking {
|
||||||
|
Property::query()->whereKey($property->id)->lockForUpdate()->firstOrFail();
|
||||||
|
|
||||||
|
if ($evidence !== null) {
|
||||||
|
$evidence = BlockedPeriod::query()->whereKey($evidence->id)->lockForUpdate()->firstOrFail();
|
||||||
|
$existing = $this->checkEvidence($evidence);
|
||||||
|
if ($existing !== null) {
|
||||||
|
return $existing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$guests = isset($facts['guests']) && (int) $facts['guests'] > 0 ? (int) $facts['guests'] : null;
|
||||||
|
$guest = $evidence?->guest ?? $this->guestFrom((array) ($facts['guest'] ?? []));
|
||||||
|
$portalTotal = isset($facts['portal_total']) && $facts['portal_total'] !== '' ? (int) $facts['portal_total'] : null;
|
||||||
|
$reference = filled($facts['portal_reference'] ?? null) ? trim((string) $facts['portal_reference']) : ($evidence?->ical_interpretation['fields']['booking_reference'] ?? null);
|
||||||
|
|
||||||
|
$booking = $property->bookings()->create([
|
||||||
|
'guest_id' => $guest?->id,
|
||||||
|
'status' => BookingStatus::Reserved,
|
||||||
|
'source' => 'portal',
|
||||||
|
'intake' => IntakeKind::Booking,
|
||||||
|
'origin_channel_id' => $evidence?->origin_channel_id ?? $channel->id,
|
||||||
|
'portal_reference' => $reference,
|
||||||
|
'arrival' => $arrival->toDateString(),
|
||||||
|
'departure' => $departure->toDateString(),
|
||||||
|
'guests' => $guests,
|
||||||
|
'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),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($evidence !== null) {
|
||||||
|
$evidence->forceFill([
|
||||||
|
'is_representation' => true, 'representation_automatic' => false, 'canonical_block_id' => null,
|
||||||
|
'linked_booking_id' => $booking->id, 'export_approved' => false, 'needs_review' => false, 'reviewed_at' => now(),
|
||||||
|
'occupation_kind' => OccupationKind::Reservation, 'guest_id' => $guest?->id,
|
||||||
|
'review_note' => 'Als Vorgang übernommen; der Vorgang führt diese Belegung.',
|
||||||
|
])->save();
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->confirm->bind($booking);
|
||||||
|
|
||||||
|
if ($evidence !== null) {
|
||||||
|
app(ReconcileChannelRepresentations::class)->handle($property);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $booking->refresh();
|
||||||
|
});
|
||||||
|
|
||||||
|
// The process core sends the documents when everything is there (automatic mode); v0.11 (E-036): the booking
|
||||||
|
// stays binding, only missing administrative details of a reachable guest are asked for.
|
||||||
|
app(ProcessRunner::class)->advance($booking, 'booking.taken_over');
|
||||||
|
|
||||||
|
return $booking->refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A portal calendar entry can become a case once: returns the case it already belongs to, or throws when the entry
|
||||||
|
* is no reservation of a portal.
|
||||||
|
*
|
||||||
|
* @throws ReservationException
|
||||||
|
*/
|
||||||
|
private function checkEvidence(BlockedPeriod $evidence): ?Booking
|
||||||
|
{
|
||||||
|
if (! in_array($evidence->source, ['channel', 'email', 'api'], true) || $evidence->channel_id === null) {
|
||||||
|
throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.');
|
||||||
|
}
|
||||||
|
if ($evidence->occupationKind() === OccupationKind::Block) {
|
||||||
|
throw new ReservationException('Eine Sperrzeit ist keine Buchung. Bitte zuerst „Einordnen“ und als Portalreservierung kennzeichnen.');
|
||||||
|
}
|
||||||
|
if ($evidence->is_representation && $evidence->linked_booking_id !== null) {
|
||||||
|
return Booking::query()->findOrFail($evidence->linked_booking_id);
|
||||||
|
}
|
||||||
|
if ($evidence->is_representation) {
|
||||||
|
throw new ReservationException('Dieser Eintrag ist die Spiegelung einer anderen Belegung. Der Vorgang gehört an die führende Belegung.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The guest the portal named – only with a real name. A known e-mail address finds the existing guest without
|
||||||
|
* overwriting his data; nothing is invented.
|
||||||
|
*
|
||||||
|
* @param array<string, ?string> $data
|
||||||
|
*/
|
||||||
|
private function guestFrom(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', 'country']));
|
||||||
|
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 ?? '']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<?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 App\Process\RequestHold;
|
||||||
|
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);
|
||||||
|
// v0.11 (B1): a portal request without the guest's details holds nothing until the details are there; the
|
||||||
|
// offer hold comes with the offer.
|
||||||
|
$draft = new Booking(['property_id' => $property->id, 'arrival' => $arrival->toDateString(), 'departure' => $departure->toDateString()]);
|
||||||
|
$draft->setRelation('guest', null);
|
||||||
|
|
||||||
|
return $property->bookings()->create([
|
||||||
|
...RequestHold::for($draft, $profile),
|
||||||
|
'status' => BookingStatus::Reserved,
|
||||||
|
'source' => 'portal',
|
||||||
|
'intake' => IntakeKind::Inquiry,
|
||||||
|
'origin_channel_id' => $channel->id,
|
||||||
|
'portal_reference' => $reference,
|
||||||
|
'arrival' => $arrival->toDateString(),
|
||||||
|
'departure' => $departure->toDateString(),
|
||||||
|
'processing_mode' => $processingMode,
|
||||||
|
'internal_notes' => $notes,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
app(CaseAutomation::class)->advance($booking);
|
||||||
|
|
||||||
|
return $booking->refresh();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,7 +21,7 @@ public function conflictsFor(BlockedPeriod $block): array
|
|||||||
$period = $block->starts_on->format('d.m.Y').' – '.$block->ends_on->format('d.m.Y');
|
$period = $block->starts_on->format('d.m.Y').' – '.$block->ends_on->format('d.m.Y');
|
||||||
|
|
||||||
$bookings = $property->bookings()->occupying()->overlapping($block->starts_on, $block->ends_on)->with('guest')->get()
|
$bookings = $property->bookings()->occupying()->overlapping($block->starts_on, $block->ends_on)->with('guest')->get()
|
||||||
->map(fn (Booking $booking): string => "{$channelName} meldet {$period}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guest->full_name}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})");
|
->map(fn (Booking $booking): string => "{$channelName} meldet {$period}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guestName()}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})");
|
||||||
|
|
||||||
$blocks = $property->blockedPeriods()
|
$blocks = $property->blockedPeriods()
|
||||||
->occupying()
|
->occupying()
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Channels\Contracts;
|
||||||
|
|
||||||
|
use App\Channels\Events\ChannelEvent;
|
||||||
|
use App\Models\Channel;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Capability of a connector whose portal offers an interface for bookings, cancellations, changes and amounts
|
||||||
|
* (Architektur V2, 02 §8.4). The events go to ChannelEventHandler; the connector itself decides nothing. Network access
|
||||||
|
* only through the Http facade (SideEffectPathsTest), so the process tester can replace it.
|
||||||
|
*/
|
||||||
|
interface DeliversEvents
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return list<ChannelEvent>
|
||||||
|
*/
|
||||||
|
public function fetchEvents(Channel $channel, ?CarbonImmutable $since): array;
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Channels\Contracts;
|
||||||
|
|
||||||
|
use App\Channels\Events\ChannelEvent;
|
||||||
|
use App\Models\Channel;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Capability of a connector whose portal pushes events (webhook). The connector verifies the signature (authenticity
|
||||||
|
* of the origin) and translates the payload; the business decision stays with ChannelEventHandler.
|
||||||
|
*/
|
||||||
|
interface ReceivesWebhooks
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return list<ChannelEvent> empty when the signature is not valid
|
||||||
|
*/
|
||||||
|
public function receive(Channel $channel, Request $request): array;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Channels\Events;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The portal reports a cancellation of a known booking: a task on the case, never a cancellation, refund or fee (E-019).
|
||||||
|
*/
|
||||||
|
final readonly class BookingCancelledByChannel extends ChannelEvent
|
||||||
|
{
|
||||||
|
public function __construct(Provenance $provenance, public ?string $note = null)
|
||||||
|
{
|
||||||
|
parent::__construct($provenance);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Channels\Events;
|
||||||
|
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The portal reports other dates or guests of a known booking: a task with the comparison, never a change of the booking.
|
||||||
|
*/
|
||||||
|
final readonly class BookingChangedByChannel extends ChannelEvent
|
||||||
|
{
|
||||||
|
public function __construct(Provenance $provenance, public ?CarbonImmutable $arrival = null, public ?CarbonImmutable $departure = null, public ?int $guests = null)
|
||||||
|
{
|
||||||
|
parent::__construct($provenance);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Channels\Events;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A normalised business event of a portal, independent of its transport (Architektur V2, K4/K10). Future API or
|
||||||
|
* webhook adapters deliver these; ChannelEventHandler maps them onto the existing intake, so duplicates, origin and the
|
||||||
|
* external binding are judged in one place for every transport.
|
||||||
|
*/
|
||||||
|
abstract readonly class ChannelEvent
|
||||||
|
{
|
||||||
|
public function __construct(public Provenance $provenance) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Channels\Events;
|
||||||
|
|
||||||
|
use App\Actions\RecordPortalAmounts;
|
||||||
|
use App\Channels\Intake\IntakeDecision;
|
||||||
|
use App\Channels\Intake\PortalIntake;
|
||||||
|
use App\Enums\IntakeOutcome;
|
||||||
|
use App\Models\BlockedPeriod;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\IntakeObservation;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Support\Money;
|
||||||
|
use App\Tenancy\TenantContext;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The one entry of channel events (docs/Prozessarchitektur/Architektur/02 §8.3–8.4): maps each normalised event onto
|
||||||
|
* the existing intake, so iCal, mail and future APIs are judged by the same rules – duplicates and certainty in
|
||||||
|
* PortalIntake, amounts in RecordPortalAmounts, reports about known cases as tasks. Contains no decision rules of its
|
||||||
|
* own and never changes a binding booking (stage M4 needs the landlord's action).
|
||||||
|
*/
|
||||||
|
final class ChannelEventHandler
|
||||||
|
{
|
||||||
|
public function __construct(private PortalIntake $intake, private RecordPortalAmounts $amounts) {}
|
||||||
|
|
||||||
|
public function handle(ChannelEvent $event): ?IntakeDecision
|
||||||
|
{
|
||||||
|
$channel = $event->provenance->channel;
|
||||||
|
if (! $channel->isPortal() || $channel->tenant_id === null) {
|
||||||
|
throw new InvalidArgumentException('Kanalereignisse kommen nur von Portalen.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return app(TenantContext::class)->run($channel->tenant, fn (): ?IntakeDecision => match (true) {
|
||||||
|
$event instanceof IncomingBooking => $this->booking($event),
|
||||||
|
$event instanceof BookingCancelledByChannel => $this->report($event, IntakeOutcome::CancellationSignal, $channel->name.' meldet über die Schnittstelle eine Stornierung'.($event->note ? ' ('.$event->note.')' : '').'. Bitte prüfen Sie die Buchung und die nächsten Schritte.'),
|
||||||
|
$event instanceof BookingChangedByChannel => $this->report($event, IntakeOutcome::ChangeSignal, $channel->name.' meldet über die Schnittstelle eine Änderung'.($event->arrival && $event->departure ? ': '.$event->arrival->format('d.m.').'–'.$event->departure->format('d.m.Y') : '').($event->guests ? ', '.$event->guests.' Personen' : '').'. Die Buchung bleibt unverändert, bis Sie entscheiden.'),
|
||||||
|
$event instanceof PaymentReported => $this->payment($event),
|
||||||
|
$event instanceof PayoutReported => $this->payout($event),
|
||||||
|
default => throw new InvalidArgumentException('Unbekanntes Kanalereignis '.$event::class.'.'),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A booking binding at the portal: blocked like a booking e-mail – source api, reference in the identifier – and judged
|
||||||
|
* by PortalIntake – the same case, never a second one; a case only when certain.
|
||||||
|
*/
|
||||||
|
private function booking(IncomingBooking $event): IntakeDecision
|
||||||
|
{
|
||||||
|
$provenance = $event->provenance;
|
||||||
|
$reference = $provenance->externalReference;
|
||||||
|
// The reference is the identity of the block (as for booking mails); without one it is never taken as a reference.
|
||||||
|
$uid = $reference !== null ? 'api:'.$reference : 'api-event:'.$provenance->evidenceRef;
|
||||||
|
$block = $provenance->channel->blockedPeriods()->withTrashed()->where('source', 'api')->where('external_uid', $uid)->first()
|
||||||
|
?? new BlockedPeriod(['property_id' => $provenance->channel->property_id, 'source' => 'api', 'reason' => $provenance->channel->name, 'external_uid' => $uid]);
|
||||||
|
$block->fill(['starts_on' => $event->arrival->toDateString(), 'ends_on' => $event->departure->toDateString()]);
|
||||||
|
if ($block->trashed()) {
|
||||||
|
$block->restore();
|
||||||
|
}
|
||||||
|
$provenance->channel->blockedPeriods()->save($block);
|
||||||
|
|
||||||
|
return $this->intake->process($block->fresh(), IntakeObservation::SOURCE_API);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function report(BookingCancelledByChannel|BookingChangedByChannel $event, IntakeOutcome $outcome, string $message): ?IntakeDecision
|
||||||
|
{
|
||||||
|
$case = $this->case($event);
|
||||||
|
if ($case === null) {
|
||||||
|
return new IntakeDecision(IntakeOutcome::Clarify, ['Keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference);
|
||||||
|
}
|
||||||
|
$this->intake->reportToCase($event->provenance->channel, $case, $outcome, $message, 'api:'.$event->provenance->evidenceRef, IntakeObservation::SOURCE_API);
|
||||||
|
|
||||||
|
return new IntakeDecision($outcome, [$message], $case, reference: $event->provenance->externalReference);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function payment(PaymentReported $event): ?IntakeDecision
|
||||||
|
{
|
||||||
|
$case = $this->case($event);
|
||||||
|
if ($case === null) {
|
||||||
|
return new IntakeDecision(IntakeOutcome::Clarify, ['Zahlungsmeldung keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference);
|
||||||
|
}
|
||||||
|
$this->amounts->handle($case, null, [], [['amount' => $event->amount, 'paid_on' => $event->paidOn->toDateString()]], $event->provenance->channel->name);
|
||||||
|
|
||||||
|
return new IntakeDecision(IntakeOutcome::Link, ['Zahlung des Gastes laut Portal erfasst (kein Eingang auf unserem Konto).'], $case);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function payout(PayoutReported $event): ?IntakeDecision
|
||||||
|
{
|
||||||
|
$case = $this->case($event);
|
||||||
|
if ($case === null) {
|
||||||
|
return new IntakeDecision(IntakeOutcome::Clarify, ['Auszahlungsmeldung keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference);
|
||||||
|
}
|
||||||
|
if ($event->executed) {
|
||||||
|
// Evidence level "laut Portal erledigt" – the receipt on our account is recorded by the landlord (O5).
|
||||||
|
CaseLog::record($case, 'evidence', 'Auszahlung laut '.$event->provenance->channel->name.' ausgeführt: '.Money::format($event->amount).' am '.$event->paidOn->format('d.m.Y').' – Eingang auf unserem Konto noch nicht erfasst.', data: ['module' => 'portal.payout', 'level' => 'stated_by_portal', 'source' => $event->provenance->transport, 'ref' => $event->provenance->evidenceRef], actor: $event->provenance->channel->name);
|
||||||
|
} else {
|
||||||
|
$this->amounts->handle($case, null, [['kind' => 'payout_announced', 'amount' => $event->amount, 'due_on' => $event->paidOn->toDateString()]], [], $event->provenance->channel->name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new IntakeDecision(IntakeOutcome::Link, ['Auszahlung laut Portal vermerkt.'], $case);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The binding case of the event: by the portal's booking reference only (no merging by dates for reports).
|
||||||
|
*/
|
||||||
|
private function case(ChannelEvent $event): ?Booking
|
||||||
|
{
|
||||||
|
$reference = $event->provenance->externalReference;
|
||||||
|
$case = $reference === null ? null : $this->intake->caseByReference($event->provenance->channel, $reference);
|
||||||
|
|
||||||
|
return $case !== null && $case->isBinding() ? $case : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Channels\Events;
|
||||||
|
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A booking binding at the portal (M1/M2): its dates and reference; becomes a case only through PortalIntake's certainty rules.
|
||||||
|
*/
|
||||||
|
final readonly class IncomingBooking extends ChannelEvent
|
||||||
|
{
|
||||||
|
public function __construct(Provenance $provenance, public CarbonImmutable $arrival, public CarbonImmutable $departure, public ?int $guests = null, public ?int $total = null)
|
||||||
|
{
|
||||||
|
parent::__construct($provenance);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Channels\Events;
|
||||||
|
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The portal reports a payment of the guest to the portal: recorded "laut Portal" (GuestViaPortal), never as money on our account.
|
||||||
|
*/
|
||||||
|
final readonly class PaymentReported extends ChannelEvent
|
||||||
|
{
|
||||||
|
public function __construct(Provenance $provenance, public int $amount, public CarbonImmutable $paidOn)
|
||||||
|
{
|
||||||
|
parent::__construct($provenance);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Channels\Events;
|
||||||
|
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The portal announces or reports a payout to us: "laut Portal" only – a received payout is recorded by the landlord (decision O5).
|
||||||
|
*/
|
||||||
|
final readonly class PayoutReported extends ChannelEvent
|
||||||
|
{
|
||||||
|
public function __construct(Provenance $provenance, public int $amount, public CarbonImmutable $paidOn, public bool $executed = false)
|
||||||
|
{
|
||||||
|
parent::__construct($provenance);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Channels\Events;
|
||||||
|
|
||||||
|
use App\Models\Channel;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a channel event came from (docs/Prozessarchitektur/Architektur/02 §8.2): channel, transport and whether its
|
||||||
|
* origin is technically authenticated (a signed webhook, an API call with credentials). It says nothing about whether a
|
||||||
|
* business action really happened – that is evidence, which only the landlord or a checked receipt provides (M3).
|
||||||
|
*/
|
||||||
|
final readonly class Provenance
|
||||||
|
{
|
||||||
|
public const AUTHENTICATED = 'authenticated';
|
||||||
|
|
||||||
|
public const UNAUTHENTICATED = 'unauthenticated';
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
public Channel $channel,
|
||||||
|
public string $transport,
|
||||||
|
public string $authenticity,
|
||||||
|
public ?string $externalReference,
|
||||||
|
public string $evidenceRef,
|
||||||
|
public CarbonImmutable $receivedAt,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function isAuthenticated(): bool
|
||||||
|
{
|
||||||
|
return $this->authenticity === self::AUTHENTICATED;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -41,6 +41,16 @@ public function properties(Channel $channel, Booking|BlockedPeriod $occupation):
|
|||||||
/** @return array<string, string|null> */
|
/** @return array<string, string|null> */
|
||||||
public function context(Booking|BlockedPeriod $occupation): array
|
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;
|
$booking = $occupation instanceof Booking;
|
||||||
$start = $booking ? $occupation->arrival : $occupation->starts_on;
|
$start = $booking ? $occupation->arrival : $occupation->starts_on;
|
||||||
$end = $booking ? $occupation->departure : $occupation->ends_on;
|
$end = $booking ? $occupation->departure : $occupation->ends_on;
|
||||||
|
|||||||
@@ -33,7 +33,8 @@ public function build(Channel $channel): string
|
|||||||
}
|
}
|
||||||
foreach ($bookings->with(['guest', 'property'])->orderBy('id')->get() as $booking) {
|
foreach ($bookings->with(['guest', 'property'])->orderBy('id')->get() as $booking) {
|
||||||
/** @var Booking $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()
|
$blocks = $property->blockedPeriods()
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,506 @@
|
|||||||
|
<?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', 'api'], 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 report of the portal about a known case (channel events, Architektur V2: cancellation or change via an API):
|
||||||
|
* the case gets a task and a history entry, nothing about the booking changes (E-019, stage M2 of 02 §8.2).
|
||||||
|
*/
|
||||||
|
public function reportToCase(Channel $channel, Booking $case, IntakeOutcome $outcome, string $message, string $key, string $source): void
|
||||||
|
{
|
||||||
|
$this->report($channel, $channel->case_intake ?? CaseIntakeMode::Off, $case, $outcome, $message, $key, $source);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A block of a portal's API (channel events, Architektur V2) carries the reference like a booking mail.
|
||||||
|
if ($block->source === 'api' && str_starts_with((string) $block->external_uid, 'api:')) {
|
||||||
|
return substr((string) $block->external_uid, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
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, 'api:'.$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;
|
||||||
|
}
|
||||||
|
if ($block->source === 'api') {
|
||||||
|
return $reference === null ? 'Portalmeldung ohne Buchungsnummer – keinem Vorgang sicher zuzuordnen.' : 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,9 @@
|
|||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Illuminate\Support\Facades\Cache;
|
use Illuminate\Support\Facades\Cache;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
|
use Webklex\PHPIMAP\Client;
|
||||||
use Webklex\PHPIMAP\ClientManager;
|
use Webklex\PHPIMAP\ClientManager;
|
||||||
|
use Webklex\PHPIMAP\Folder;
|
||||||
use Webklex\PHPIMAP\Message;
|
use Webklex\PHPIMAP\Message;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -70,7 +72,7 @@ public function fetch(array $senders): array
|
|||||||
'protocol' => 'imap',
|
'protocol' => 'imap',
|
||||||
]);
|
]);
|
||||||
$client->connect();
|
$client->connect();
|
||||||
$folder = $client->getFolderByPath($config['folder']);
|
$folder = self::folder($client, $config['folder']);
|
||||||
|
|
||||||
$mails = [];
|
$mails = [];
|
||||||
foreach ($senders as $sender) {
|
foreach ($senders as $sender) {
|
||||||
@@ -98,6 +100,97 @@ public function fetch(array $senders): array
|
|||||||
return $mails;
|
return $mails;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every message of the last days (v0.11 inbox, mailbox mode "full"), left unread. Deduplication happens when the
|
||||||
|
* messages are stored.
|
||||||
|
*
|
||||||
|
* @return list<PortalMail>
|
||||||
|
*
|
||||||
|
* @throws ChannelSyncException
|
||||||
|
*/
|
||||||
|
public function fetchAll(): array
|
||||||
|
{
|
||||||
|
$config = self::configuration();
|
||||||
|
if ($config === null) {
|
||||||
|
throw new ChannelSyncException('Für diesen Mandanten ist kein Postfach hinterlegt.');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$client = (new ClientManager)->make([
|
||||||
|
'host' => $config['host'], 'port' => $config['port'], 'encryption' => $config['encryption'], 'validate_cert' => true,
|
||||||
|
'username' => $config['username'], 'password' => $config['password'], 'protocol' => 'imap',
|
||||||
|
]);
|
||||||
|
$client->connect();
|
||||||
|
$messages = self::folder($client, $config['folder'])->query()
|
||||||
|
->whereSince(CarbonImmutable::today()->subDays((int) config('fewo.mailbox.lookback_days', 3)))
|
||||||
|
->leaveUnread()
|
||||||
|
->get();
|
||||||
|
$mails = [];
|
||||||
|
foreach ($messages as $message) {
|
||||||
|
$mails[] = $this->toPortalMail($message);
|
||||||
|
}
|
||||||
|
$client->disconnect();
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
Cache::forever(self::key(self::LAST_ERROR_KEY), $exception->getMessage());
|
||||||
|
|
||||||
|
throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
Cache::forever(self::key(self::LAST_SUCCESS_KEY), now()->toIso8601String());
|
||||||
|
Cache::forget(self::key(self::LAST_ERROR_KEY));
|
||||||
|
|
||||||
|
return $mails;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connects with the given connection data and counts the messages of the last days (check on System › Betrieb).
|
||||||
|
* Nothing is read, marked or stored.
|
||||||
|
*
|
||||||
|
* @param array{host: string, port: int, encryption: string, username: string, password: ?string, folder: string} $config
|
||||||
|
*
|
||||||
|
* @throws ChannelSyncException
|
||||||
|
*/
|
||||||
|
public function probe(array $config): int
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$client = (new ClientManager)->make([
|
||||||
|
'host' => $config['host'], 'port' => $config['port'], 'encryption' => $config['encryption'], 'validate_cert' => true,
|
||||||
|
'username' => $config['username'], 'password' => $config['password'], 'protocol' => 'imap',
|
||||||
|
]);
|
||||||
|
$client->connect();
|
||||||
|
$count = self::folder($client, $config['folder'])->query()
|
||||||
|
->whereSince(CarbonImmutable::today()->subDays((int) config('fewo.mailbox.lookback_days', 3)))
|
||||||
|
->leaveUnread()->setFetchBody(false)->count();
|
||||||
|
$client->disconnect();
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
throw new ChannelSyncException('Postfach nicht erreichbar: '.$exception->getMessage(), previous: $exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (int) $count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The folder to read. The inbox is called "INBOX" on the IMAP server, whatever the provider's web mail shows
|
||||||
|
* ("Posteingang", "Inbox"); other names match regardless of case. An unknown name names the existing folders.
|
||||||
|
*
|
||||||
|
* @throws ChannelSyncException
|
||||||
|
*/
|
||||||
|
public static function folder(Client $client, ?string $name): Folder
|
||||||
|
{
|
||||||
|
$name = trim((string) $name);
|
||||||
|
$wanted = $name === '' || in_array(mb_strtolower($name), ['inbox', 'posteingang'], true) ? 'INBOX' : $name;
|
||||||
|
|
||||||
|
$folders = $client->getFolders(false);
|
||||||
|
$folder = $folders->first(fn (Folder $folder): bool => $folder->path === $wanted)
|
||||||
|
?? $folders->first(fn (Folder $folder): bool => mb_strtolower($folder->path) === mb_strtolower($wanted) || mb_strtolower($folder->name) === mb_strtolower($wanted));
|
||||||
|
|
||||||
|
if ($folder === null) {
|
||||||
|
throw new ChannelSyncException('Ordner „'.$name.'“ gibt es in diesem Postfach nicht. Vorhanden: '.$folders->map(fn (Folder $folder): string => $folder->path)->implode(', ').' (der Posteingang heißt „INBOX“).');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $folder;
|
||||||
|
}
|
||||||
|
|
||||||
private function toPortalMail(Message $message): PortalMail
|
private function toPortalMail(Message $message): PortalMail
|
||||||
{
|
{
|
||||||
$text = $message->getTextBody();
|
$text = $message->getTextBody();
|
||||||
@@ -108,12 +201,18 @@ private function toPortalMail(Message $message): PortalMail
|
|||||||
$from = $message->getFrom()->first();
|
$from = $message->getFrom()->first();
|
||||||
$date = $message->getDate()->first();
|
$date = $message->getDate()->first();
|
||||||
|
|
||||||
|
$references = preg_split('/\s+/', trim((string) $message->getReferences()?->first())) ?: [];
|
||||||
|
|
||||||
return new PortalMail(
|
return new PortalMail(
|
||||||
messageId: (string) ($message->getMessageId()->first() ?: sha1($message->getSubject()->first().$date)),
|
messageId: (string) ($message->getMessageId()->first() ?: sha1($message->getSubject()->first().$date)),
|
||||||
from: (string) ($from->mail ?? ''),
|
from: (string) ($from->mail ?? ''),
|
||||||
subject: (string) $message->getSubject()->first(),
|
subject: (string) $message->getSubject()->first(),
|
||||||
text: $text,
|
text: $text,
|
||||||
receivedAt: $date ? CarbonImmutable::instance($date) : CarbonImmutable::now(),
|
receivedAt: $date ? CarbonImmutable::instance($date) : CarbonImmutable::now(),
|
||||||
|
inReplyTo: ($reply = trim((string) $message->getInReplyTo()?->first())) !== '' ? $reply : null,
|
||||||
|
references: array_values(array_filter($references)),
|
||||||
|
to: collect($message->getTo()?->all() ?? [])->map(fn ($address): string => mb_strtolower((string) ($address->mail ?? '')))->filter()->values()->all(),
|
||||||
|
fromName: filled($from->personal ?? null) ? (string) $from->personal : null,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,15 +5,24 @@
|
|||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An incoming e-mail as delivered by the mailbox reader or the n8n webhook.
|
* An incoming e-mail as delivered by the mailbox reader or the n8n webhook. The reply references, recipients and the
|
||||||
|
* sender's name are only filled when the whole mailbox is read (v0.11 inbox).
|
||||||
*/
|
*/
|
||||||
final readonly class PortalMail
|
final readonly class PortalMail
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* @param list<string> $references
|
||||||
|
* @param list<string> $to
|
||||||
|
*/
|
||||||
public function __construct(
|
public function __construct(
|
||||||
public string $messageId,
|
public string $messageId,
|
||||||
public string $from,
|
public string $from,
|
||||||
public string $subject,
|
public string $subject,
|
||||||
public string $text,
|
public string $text,
|
||||||
public CarbonImmutable $receivedAt,
|
public CarbonImmutable $receivedAt,
|
||||||
|
public ?string $inReplyTo = null,
|
||||||
|
public array $references = [],
|
||||||
|
public array $to = [],
|
||||||
|
public ?string $fromName = null,
|
||||||
) {}
|
) {}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication;
|
||||||
|
|
||||||
|
use App\Enums\Medium;
|
||||||
|
use App\Enums\MessageEffect;
|
||||||
|
use App\Enums\MessageIntent;
|
||||||
|
use App\Support\Settings;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The medium × intent policy (V2.1): `config/communication.php` is the ceiling, the landlord's `communication_rules`
|
||||||
|
* (tenants) may only narrow it: switch a medium off, withdraw effects. Widening is ignored.
|
||||||
|
*/
|
||||||
|
class CommunicationRules
|
||||||
|
{
|
||||||
|
public function mediumActive(Medium $medium): bool
|
||||||
|
{
|
||||||
|
$ceiling = (bool) config("communication.media.{$medium->value}.active", false);
|
||||||
|
|
||||||
|
return $ceiling && ($this->narrowing()['media'][$medium->value]['active'] ?? true) !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function consentRequired(Medium $medium): bool
|
||||||
|
{
|
||||||
|
return (bool) config("communication.media.{$medium->value}.consent_required", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<MessageEffect> the effects the rules allow for the intent on the medium (never empty: review at least)
|
||||||
|
*/
|
||||||
|
public function effects(Medium $medium, MessageIntent $intent): array
|
||||||
|
{
|
||||||
|
/** @var list<MessageEffect> $ceiling */
|
||||||
|
$ceiling = config('communication.effects.'.$intent->value, [MessageEffect::Review]);
|
||||||
|
$withdrawn = (array) ($this->narrowing()['effects'][$medium->value][$intent->value] ?? []);
|
||||||
|
$allowed = array_values(array_filter($ceiling, fn (MessageEffect $effect): bool => ! in_array($effect->value, $withdrawn, true)));
|
||||||
|
|
||||||
|
return $allowed === [] ? [MessageEffect::Review] : $allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
private function narrowing(): array
|
||||||
|
{
|
||||||
|
return (array) (Settings::tenant()?->communication_rules ?? []);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication\Extraction;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The provider rejected the landlord's access (invalid key, no credit, no permission). The message never contains the
|
||||||
|
* key.
|
||||||
|
*/
|
||||||
|
class AccessRejected extends ExtractionFailed {}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication\Extraction;
|
||||||
|
|
||||||
|
use App\Enums\TenantServiceKey;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\TenantService;
|
||||||
|
use App\Tenancy\TenantFeatures;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A landlord's own AI access (bring your own key): provider, key and the two models of the extraction. There is no
|
||||||
|
* central operator key and no built-in model – without a complete access, or after the provider rejected the key,
|
||||||
|
* the extraction is off and messages go to the landlord.
|
||||||
|
*/
|
||||||
|
final class AiAccess
|
||||||
|
{
|
||||||
|
public const OK = 'ok';
|
||||||
|
|
||||||
|
public const INVALID = 'invalid';
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
public readonly AiProvider $provider,
|
||||||
|
#[\SensitiveParameter] public readonly string $key,
|
||||||
|
public readonly string $smallModel,
|
||||||
|
public readonly string $reviewModel,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The usable access of a landlord, or null (service off, incomplete, or rejected by the provider).
|
||||||
|
*/
|
||||||
|
public static function for(?Tenant $tenant): ?self
|
||||||
|
{
|
||||||
|
if ($tenant === null || ! app(TenantFeatures::class)->enabled(TenantServiceKey::AiGuestMail, $tenant)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$service = self::service($tenant);
|
||||||
|
if ($service === null || $service->check_status === self::INVALID) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::fromService($service);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The access as configured, regardless of the last check (for the check itself).
|
||||||
|
*/
|
||||||
|
public static function fromService(TenantService $service): ?self
|
||||||
|
{
|
||||||
|
$settings = (array) $service->settings;
|
||||||
|
$provider = AiProvider::tryFrom((string) ($settings['provider'] ?? ''));
|
||||||
|
$small = trim((string) ($settings['small_model'] ?? ''));
|
||||||
|
$review = trim((string) ($settings['review_model'] ?? ''));
|
||||||
|
if ($provider === null || blank($service->api_key) || $small === '' || $review === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new self($provider, (string) $service->api_key, $small, $review);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function service(Tenant $tenant): ?TenantService
|
||||||
|
{
|
||||||
|
return TenantService::query()->where('tenant_id', $tenant->id)->where('service', TenantServiceKey::AiGuestMail->value)->first();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The provider rejected the key: the extraction stays off until the landlord saves or checks the access again.
|
||||||
|
*/
|
||||||
|
public static function markInvalid(Tenant $tenant, string $message): void
|
||||||
|
{
|
||||||
|
self::service($tenant)?->forceFill(['check_status' => self::INVALID, 'check_message' => mb_substr($message, 0, 500), 'checked_at' => now()])->save();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __debugInfo(): array
|
||||||
|
{
|
||||||
|
return ['provider' => $this->provider->value, 'key' => '***', 'smallModel' => $this->smallModel, 'reviewModel' => $this->reviewModel];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication\Extraction;
|
||||||
|
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The AI providers a landlord may connect (bring your own key, v0.11). Endpoints are fixed here – no configuration,
|
||||||
|
* form or environment value can point the extraction at another host.
|
||||||
|
*/
|
||||||
|
enum AiProvider: string implements HasLabel
|
||||||
|
{
|
||||||
|
case Anthropic = 'anthropic';
|
||||||
|
case OpenRouter = 'openrouter';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Anthropic => 'Anthropic (Claude API)',
|
||||||
|
self::OpenRouter => 'OpenRouter',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public function endpoint(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Anthropic => 'https://api.anthropic.com/v1/messages',
|
||||||
|
self::OpenRouter => 'https://openrouter.ai/api/v1/chat/completions',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Examples for the form – suggestions only, nothing is preset.
|
||||||
|
*/
|
||||||
|
public function modelExamples(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Anthropic => 'z. B. klein „claude-haiku-5-5“, groß „claude-opus-5-5“',
|
||||||
|
self::OpenRouter => 'z. B. klein „anthropic/claude-haiku-5-5“, groß „anthropic/claude-opus-5-5“ (Kennung wie bei OpenRouter angezeigt)',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication\Extraction;
|
||||||
|
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The extraction could not produce a usable result (no key, timeout, refusal, invalid output). The message then
|
||||||
|
* waits for the landlord – the safe fallback of CH-14.
|
||||||
|
*/
|
||||||
|
class ExtractionFailed extends RuntimeException {}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication\Extraction;
|
||||||
|
|
||||||
|
use Illuminate\Http\Client\ConnectionException;
|
||||||
|
use Illuminate\Http\Client\RequestException;
|
||||||
|
use Illuminate\Http\Client\Response;
|
||||||
|
use Illuminate\Support\Facades\Http;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The model connection of the extraction with the landlord's own access (bring your own key, v0.11): Anthropic's
|
||||||
|
* Messages API or OpenRouter's chat completions, both over HTTP to the provider's fixed endpoint (AiProvider), no SDK
|
||||||
|
* dependency. One call: system prompt, the message, and a JSON schema the answer must follow (structured outputs).
|
||||||
|
* The key travels only in the request header; it is never part of an exception, a log line or a stored result.
|
||||||
|
*/
|
||||||
|
class LlmClient
|
||||||
|
{
|
||||||
|
/** Server-side refusal fallback on Anthropic (opt-in default for the Claude Opus family). */
|
||||||
|
private const ANTHROPIC_FALLBACK_BETA = 'server-side-fallback-2026-07-01';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $schema
|
||||||
|
* @return array{data: array<string, mixed>, model: string, usage: array<string, mixed>}
|
||||||
|
*
|
||||||
|
* @throws AccessRejected when the provider rejects the access
|
||||||
|
* @throws ExtractionFailed for every other unusable outcome
|
||||||
|
*/
|
||||||
|
public function structured(AiAccess $access, string $model, string $system, string $message, array $schema, string $effort = 'medium'): array
|
||||||
|
{
|
||||||
|
[$headers, $body] = match ($access->provider) {
|
||||||
|
AiProvider::Anthropic => $this->anthropic($access, $model, $system, $message, $schema, $effort),
|
||||||
|
AiProvider::OpenRouter => $this->openRouter($access, $model, $system, $message, $schema),
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = Http::withHeaders($headers)
|
||||||
|
->timeout((int) config('fewo.ai.timeout', 40))
|
||||||
|
// Only passing problems are repeated; a rejected key or a bad request is not.
|
||||||
|
->retry(2, 2000, fn (Throwable $exception): bool => $exception instanceof ConnectionException || ($exception instanceof RequestException && in_array($exception->response->status(), [429, 500, 502, 503, 529], true)), throw: false)
|
||||||
|
->post($access->provider->endpoint(), $body);
|
||||||
|
} catch (ConnectionException) {
|
||||||
|
throw new ExtractionFailed('Keine Verbindung zu '.$access->provider->getLabel().'.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_array($response->status(), [401, 402, 403], true)) {
|
||||||
|
throw new AccessRejected($access->provider->getLabel().' lehnt den Zugang ab ('.$response->status().': '.$this->providerMessage($response, $access).').');
|
||||||
|
}
|
||||||
|
if (! $response->successful()) {
|
||||||
|
throw new ExtractionFailed($access->provider->getLabel().' antwortet mit '.$response->status().' ('.$this->providerMessage($response, $access).').');
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = (array) $response->json();
|
||||||
|
$text = $access->provider === AiProvider::Anthropic ? $this->anthropicText($payload) : $this->openRouterText($payload);
|
||||||
|
$data = json_decode($text, true);
|
||||||
|
if (! is_array($data)) {
|
||||||
|
throw new ExtractionFailed('Die Antwort ist kein gültiges JSON.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['data' => $data, 'model' => (string) ($payload['model'] ?? $model), 'usage' => (array) ($payload['usage'] ?? [])];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $schema
|
||||||
|
* @return array{0: array<string, string>, 1: array<string, mixed>}
|
||||||
|
*/
|
||||||
|
private function anthropic(AiAccess $access, string $model, string $system, string $message, array $schema, string $effort): array
|
||||||
|
{
|
||||||
|
$headers = ['x-api-key' => $access->key, 'anthropic-version' => (string) config('fewo.ai.anthropic_version'), 'content-type' => 'application/json'];
|
||||||
|
$body = [
|
||||||
|
'model' => $model,
|
||||||
|
'max_tokens' => 4096,
|
||||||
|
'system' => $system,
|
||||||
|
'messages' => [['role' => 'user', 'content' => $message]],
|
||||||
|
'output_config' => ['effort' => $effort, 'format' => ['type' => 'json_schema', 'schema' => $schema]],
|
||||||
|
];
|
||||||
|
if (str_starts_with($model, 'claude-opus-')) {
|
||||||
|
$body['fallbacks'] = 'default';
|
||||||
|
$headers['anthropic-beta'] = self::ANTHROPIC_FALLBACK_BETA;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$headers, $body];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $schema
|
||||||
|
* @return array{0: array<string, string>, 1: array<string, mixed>}
|
||||||
|
*/
|
||||||
|
private function openRouter(AiAccess $access, string $model, string $system, string $message, array $schema): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
['Authorization' => 'Bearer '.$access->key, 'content-type' => 'application/json', 'HTTP-Referer' => (string) config('app.url'), 'X-OpenRouter-Title' => 'FewoPortal'],
|
||||||
|
[
|
||||||
|
'model' => $model,
|
||||||
|
'max_tokens' => 4096,
|
||||||
|
'messages' => [['role' => 'system', 'content' => $system], ['role' => 'user', 'content' => $message]],
|
||||||
|
'response_format' => ['type' => 'json_schema', 'json_schema' => ['name' => 'extraction', 'strict' => true, 'schema' => $schema]],
|
||||||
|
// Only providers that honour the schema; otherwise it would merely be a hint.
|
||||||
|
'provider' => ['require_parameters' => true],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $payload
|
||||||
|
*/
|
||||||
|
private function anthropicText(array $payload): string
|
||||||
|
{
|
||||||
|
match ($payload['stop_reason'] ?? null) {
|
||||||
|
'refusal' => throw new ExtractionFailed('Der Anbieter hat die Auswertung abgelehnt.'),
|
||||||
|
'max_tokens' => throw new ExtractionFailed('Die Antwort ist unvollständig.'),
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
return collect((array) ($payload['content'] ?? []))->where('type', 'text')->pluck('text')->implode('');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $payload
|
||||||
|
*/
|
||||||
|
private function openRouterText(array $payload): string
|
||||||
|
{
|
||||||
|
$choice = (array) ($payload['choices'][0] ?? []);
|
||||||
|
match ($choice['finish_reason'] ?? null) {
|
||||||
|
'content_filter' => throw new ExtractionFailed('Der Anbieter hat die Auswertung abgelehnt.'),
|
||||||
|
'length' => throw new ExtractionFailed('Die Antwort ist unvollständig.'),
|
||||||
|
'error' => throw new ExtractionFailed('Der Anbieter meldet einen Fehler.'),
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (string) ($choice['message']['content'] ?? '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The provider's own short message, cut and without anything that looks like a key.
|
||||||
|
*/
|
||||||
|
private function providerMessage(Response $response, AiAccess $access): string
|
||||||
|
{
|
||||||
|
$message = str_replace($access->key, '***', (string) ($response->json('error.message') ?? $response->json('error.type') ?? ''));
|
||||||
|
|
||||||
|
return mb_substr((string) preg_replace('/(sk-[A-Za-z0-9_\-]{6})[A-Za-z0-9_\-]+/', '$1…', $message), 0, 200) ?: 'ohne Angabe';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication\Extraction;
|
||||||
|
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\InboundMessage;
|
||||||
|
use App\Process\CaseRequirements;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The model side of the extraction (v0.11, CH-14): versioned prompts with defined placeholders, a JSON schema for the
|
||||||
|
* answer and its validation here (the answer is checked, not trusted). The small model extracts; the review model
|
||||||
|
* sees the original and the first extraction – both as configured in the landlord's own access. Both only return
|
||||||
|
* candidates – nothing is stored or changed here.
|
||||||
|
*/
|
||||||
|
class MessageExtractor
|
||||||
|
{
|
||||||
|
public function __construct(private LlmClient $client) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{data: array{facts: list<array{field: string, value: string, evidence: string, confidence: float|int}>, change_requests: list<array{field: string, value: string, evidence: string}>, intent: string, uncertainties: list<string>}, model: string}
|
||||||
|
*
|
||||||
|
* @throws ExtractionFailed
|
||||||
|
*/
|
||||||
|
public function extract(AiAccess $access, InboundMessage $message, Booking $booking): array
|
||||||
|
{
|
||||||
|
return $this->call($access, $access->smallModel, $this->prompt('', $booking), $this->messageText($message), 'medium');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $first
|
||||||
|
* @return array{data: array{facts: list<array{field: string, value: string, evidence: string, confidence: float|int}>, change_requests: list<array{field: string, value: string, evidence: string}>, intent: string, uncertainties: list<string>}, model: string}
|
||||||
|
*
|
||||||
|
* @throws ExtractionFailed
|
||||||
|
*/
|
||||||
|
public function review(AiAccess $access, InboundMessage $message, Booking $booking, array $first): array
|
||||||
|
{
|
||||||
|
return $this->call($access, $access->reviewModel, $this->prompt('-review', $booking, ['first_extraction' => json_encode($first, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)]), $this->messageText($message), 'high');
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function promptVersion(): string
|
||||||
|
{
|
||||||
|
return (string) config('fewo.ai.prompt_version', 'v1');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The prompt of the configured version with every placeholder filled; an unknown placeholder is an error.
|
||||||
|
*
|
||||||
|
* @param array<string, string> $extra
|
||||||
|
*/
|
||||||
|
public function prompt(string $variant, Booking $booking, array $extra = []): string
|
||||||
|
{
|
||||||
|
$path = resource_path('prompts/extraction/'.self::promptVersion().$variant.'.md');
|
||||||
|
if (! is_file($path)) {
|
||||||
|
throw new ExtractionFailed('Prompt '.self::promptVersion().$variant.' fehlt.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$values = [
|
||||||
|
'phase' => match (true) {
|
||||||
|
$booking->isBinding() => 'binding booking (contract exists; changes are only wishes)',
|
||||||
|
$booking->offer_version > 0 => 'binding offer sent, not yet accepted',
|
||||||
|
default => 'non-binding request',
|
||||||
|
},
|
||||||
|
'requested_fields' => implode(', ', $booking->openDataRequest()?->fields ?? CaseRequirements::missing($booking)) ?: 'none',
|
||||||
|
'known_fields' => $this->knownFields($booking),
|
||||||
|
'today' => now()->toDateString(),
|
||||||
|
...$extra,
|
||||||
|
];
|
||||||
|
|
||||||
|
$prompt = preg_replace_callback('/\{\{\s*(\w+)\s*\}\}/', function (array $match) use ($values): string {
|
||||||
|
if (! array_key_exists($match[1], $values)) {
|
||||||
|
throw new ExtractionFailed('Unbekannter Platzhalter {{'.$match[1].'}}.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $values[$match[1]];
|
||||||
|
}, (string) file_get_contents($path));
|
||||||
|
|
||||||
|
return (string) $prompt;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public static function schema(): array
|
||||||
|
{
|
||||||
|
return (array) json_decode((string) file_get_contents(resource_path('prompts/extraction/schema.json')), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{data: array{facts: list<array{field: string, value: string, evidence: string, confidence: float|int}>, change_requests: list<array{field: string, value: string, evidence: string}>, intent: string, uncertainties: list<string>}, model: string}
|
||||||
|
*/
|
||||||
|
private function call(AiAccess $access, string $model, string $system, string $text, string $effort): array
|
||||||
|
{
|
||||||
|
$schema = self::schema();
|
||||||
|
$lastError = null;
|
||||||
|
// One repetition when the answer does not fit the schema, then the message goes to the landlord.
|
||||||
|
for ($attempt = 1; $attempt <= 2; $attempt++) {
|
||||||
|
$result = $this->client->structured($access, $model, $system, $text, $schema, $effort);
|
||||||
|
$lastError = $this->violation($result['data'], $schema);
|
||||||
|
if ($lastError === null) {
|
||||||
|
return ['data' => $result['data'], 'model' => $result['model']];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new ExtractionFailed('Antwort passt nicht zum Schema: '.$lastError);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The first deviation of the answer from the schema, or null.
|
||||||
|
*
|
||||||
|
* @param array<string, mixed> $data
|
||||||
|
* @param array<string, mixed> $schema
|
||||||
|
*/
|
||||||
|
private function violation(array $data, array $schema): ?string
|
||||||
|
{
|
||||||
|
foreach ($schema['required'] as $key) {
|
||||||
|
if (! array_key_exists($key, $data)) {
|
||||||
|
return 'Feld '.$key.' fehlt';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (! is_array($data['facts']) || ! is_array($data['change_requests']) || ! is_array($data['uncertainties']) || ! is_string($data['intent'])) {
|
||||||
|
return 'falsche Typen';
|
||||||
|
}
|
||||||
|
if (! in_array($data['intent'], $schema['properties']['intent']['enum'], true)) {
|
||||||
|
return 'unbekannte Absicht';
|
||||||
|
}
|
||||||
|
foreach (['facts', 'change_requests'] as $list) {
|
||||||
|
$item = $schema['properties'][$list]['items'];
|
||||||
|
foreach ($data[$list] as $entry) {
|
||||||
|
if (! is_array($entry) || array_diff($item['required'], array_keys($entry)) !== [] || ! in_array($entry['field'], $item['properties']['field']['enum'], true)) {
|
||||||
|
return 'ungültiger Eintrag in '.$list;
|
||||||
|
}
|
||||||
|
if (! is_string($entry['value']) || ! is_string($entry['evidence']) || ($list === 'facts' && ! is_numeric($entry['confidence']))) {
|
||||||
|
return 'falscher Typ in '.$list;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function messageText(InboundMessage $message): string
|
||||||
|
{
|
||||||
|
return 'Subject: '.$message->subject."\n\n".mb_substr((string) $message->body, 0, 20000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Values on file, masked: enough to see whether something differs, not to learn the data.
|
||||||
|
*/
|
||||||
|
private function knownFields(Booking $booking): string
|
||||||
|
{
|
||||||
|
$known = [];
|
||||||
|
foreach ([...array_keys(CaseRequirements::FIELDS), ...array_keys(CaseRequirements::OPTIONAL_FIELDS)] as $field) {
|
||||||
|
$value = (string) CaseRequirements::value($booking, $field);
|
||||||
|
if ($value === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$known[] = $field.'='.(str_starts_with($field, 'booking.') ? $value : mb_substr($value, 0, 1).str_repeat('*', max(1, mb_strlen($value) - 2)).mb_substr($value, -1));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $known === [] ? 'none' : implode('; ', $known);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication\Extraction;
|
||||||
|
|
||||||
|
use App\Actions\ContributeCaseFacts;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Process\CaseRequirements;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The programmatic risk check of an extraction (v0.11, CH-14). The model's confidence is no calibrated probability:
|
||||||
|
* it may trigger a review, never waive one. Criticality comes from the field, the phase and the kind of deviation;
|
||||||
|
* contradictions and failed plausibility checks call for the review model regardless of the confidence, and are never
|
||||||
|
* taken over automatically. Thresholds are configured and calibrated with test messages (go-live condition).
|
||||||
|
*/
|
||||||
|
class RiskAssessment
|
||||||
|
{
|
||||||
|
/** Details whose automatic completion is harmless in every phase. */
|
||||||
|
private const ADMINISTRATIVE = ['guest.phone', 'booking.arrival_time'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks every fact and marks why it may not be taken over automatically.
|
||||||
|
*
|
||||||
|
* @param array{facts: list<array{field: string, value: string, evidence: string, confidence: float|int}>, change_requests: list<array{field: string, value: string, evidence: string}>, intent: string, uncertainties: list<string>} $extraction
|
||||||
|
* @return list<array{field: string, value: string, evidence: string, confidence: float, criticality: float, problems: list<string>}>
|
||||||
|
*/
|
||||||
|
public function facts(Booking $booking, string $message, array $extraction): array
|
||||||
|
{
|
||||||
|
$checked = [];
|
||||||
|
$values = [];
|
||||||
|
foreach ($extraction['facts'] as $fact) {
|
||||||
|
$values[$fact['field']][] = mb_strtolower(trim($fact['value']));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($extraction['facts'] as $fact) {
|
||||||
|
$field = $fact['field'];
|
||||||
|
$value = trim($fact['value']);
|
||||||
|
$problems = [];
|
||||||
|
|
||||||
|
if (! CaseRequirements::isValid($field, $value)) {
|
||||||
|
$problems[] = 'Wert ungültig';
|
||||||
|
}
|
||||||
|
if (! $this->evidenceFound($message, $fact['evidence'])) {
|
||||||
|
$problems[] = 'Belegstelle nicht in der Nachricht';
|
||||||
|
}
|
||||||
|
if (count(array_unique($values[$field] ?? [])) > 1) {
|
||||||
|
$problems[] = 'widersprüchliche Angaben in derselben Nachricht';
|
||||||
|
}
|
||||||
|
$current = CaseRequirements::value($booking, $field);
|
||||||
|
if (CaseRequirements::isValid($field, $current) && mb_strtolower(trim((string) $current)) !== mb_strtolower($value)) {
|
||||||
|
$problems[] = 'weicht vom gespeicherten Wert ab';
|
||||||
|
}
|
||||||
|
$problems = [...$problems, ...$this->plausibility($booking, $field, $value)];
|
||||||
|
|
||||||
|
$checked[] = [
|
||||||
|
'field' => $field,
|
||||||
|
'value' => $value,
|
||||||
|
'evidence' => $fact['evidence'],
|
||||||
|
'confidence' => max(0.0, min(1.0, (float) $fact['confidence'])),
|
||||||
|
'criticality' => $this->criticality($booking, $field),
|
||||||
|
'problems' => $problems,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $checked;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the review model has to look at the extraction: any contradiction or failed check, any wish to change
|
||||||
|
* something in a binding phase, an uncertainty the model reported, or criticality × (1 − confidence) above the
|
||||||
|
* configured threshold.
|
||||||
|
*
|
||||||
|
* @param list<array{criticality: float, confidence: float, problems: list<string>}> $facts
|
||||||
|
* @param array{change_requests: list<mixed>, uncertainties: list<string>} $extraction
|
||||||
|
*/
|
||||||
|
public function needsReview(Booking $booking, array $facts, array $extraction): bool
|
||||||
|
{
|
||||||
|
if ($extraction['uncertainties'] !== [] || ($extraction['change_requests'] !== [] && $booking->offer_version > 0)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$threshold = (float) config('fewo.ai.escalate_above', 0.2);
|
||||||
|
foreach ($facts as $fact) {
|
||||||
|
if ($fact['problems'] !== [] || $threshold < $fact['criticality'] * (1 - $fact['confidence'])) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a checked fact may go to the fact intake automatically: no problem, confident enough, the detail not
|
||||||
|
* known yet, and no stay detail (those are change requests). The intake applies its own rules on top.
|
||||||
|
*
|
||||||
|
* @param array{field: string, confidence: float, problems: list<string>} $fact
|
||||||
|
*/
|
||||||
|
public function mayTakeOver(Booking $booking, array $fact): bool
|
||||||
|
{
|
||||||
|
return $fact['problems'] === []
|
||||||
|
&& $fact['confidence'] >= (float) config('fewo.ai.min_confidence', 0.85)
|
||||||
|
&& ! in_array($fact['field'], ContributeCaseFacts::STAY_FIELDS, true)
|
||||||
|
&& ! CaseRequirements::isValid($fact['field'], CaseRequirements::value($booking, $fact['field']))
|
||||||
|
&& (in_array($fact['field'], self::ADMINISTRATIVE, true) || str_starts_with($fact['field'], 'guest.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function evidenceFound(string $message, string $evidence): bool
|
||||||
|
{
|
||||||
|
$normalise = fn (string $text): string => mb_strtolower(trim((string) preg_replace('/\s+/u', ' ', $text)));
|
||||||
|
$evidence = $normalise($evidence);
|
||||||
|
|
||||||
|
return $evidence !== '' && str_contains($normalise($message), $evidence);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function criticality(Booking $booking, string $field): float
|
||||||
|
{
|
||||||
|
return match (true) {
|
||||||
|
in_array($field, self::ADMINISTRATIVE, true) => 0.3,
|
||||||
|
in_array($field, ContributeCaseFacts::STAY_FIELDS, true), $field === 'guest.email' => 1.0,
|
||||||
|
ContributeCaseFacts::isBinding($booking) => 0.8,
|
||||||
|
default => 0.6,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
private function plausibility(Booking $booking, string $field, string $value): array
|
||||||
|
{
|
||||||
|
return match ($field) {
|
||||||
|
'booking.guests' => (int) $value > (int) $booking->property?->max_guests ? ['mehr Personen als die Wohnung fasst'] : [],
|
||||||
|
'booking.arrival', 'booking.departure' => $this->dateProblems($booking, $field, $value),
|
||||||
|
default => [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
private function dateProblems(Booking $booking, string $field, string $value): array
|
||||||
|
{
|
||||||
|
$date = rescue(fn () => CarbonImmutable::parse($value), null, false);
|
||||||
|
if ($date === null) {
|
||||||
|
return ['Datum nicht lesbar'];
|
||||||
|
}
|
||||||
|
if ($date->isBefore(CarbonImmutable::today())) {
|
||||||
|
return ['Datum liegt in der Vergangenheit'];
|
||||||
|
}
|
||||||
|
if ($field === 'booking.departure' && $booking->arrival !== null && ! $date->isAfter($booking->arrival)) {
|
||||||
|
return ['Abreise nicht nach der Anreise'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication;
|
||||||
|
|
||||||
|
use App\Enums\Medium;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A message as the medium adapters hand it over (V2.1): raw data only. {@see $verifiedBookingId} is set by the adapter
|
||||||
|
* itself from a reference it issued and can verify (signed token, reply to one of our mails) – a claim in the text is
|
||||||
|
* never enough. {@see $consentGiven} is likewise the adapter's statement.
|
||||||
|
*/
|
||||||
|
final readonly class IncomingMessage
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public Medium $medium,
|
||||||
|
public string $sender,
|
||||||
|
public string $text,
|
||||||
|
public CarbonImmutable $receivedAt,
|
||||||
|
public string $externalId,
|
||||||
|
public ?int $verifiedBookingId = null,
|
||||||
|
public bool $consentGiven = false,
|
||||||
|
public ?string $senderName = null,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication;
|
||||||
|
|
||||||
|
use App\Enums\MessageIntent;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rule-based intent of a message (V2.1). Deterministic and medium-independent; an AI classifier can later implement the
|
||||||
|
* same interface of work (E-035). Whatever the rules do not clearly recognise is {@see MessageIntent::Unclear}.
|
||||||
|
*/
|
||||||
|
class IntentClassifier
|
||||||
|
{
|
||||||
|
public function classify(string $text, bool $assignedToCase): MessageIntent
|
||||||
|
{
|
||||||
|
$text = mb_strtolower($text);
|
||||||
|
$has = fn (array $words): bool => (bool) preg_match('/('.implode('|', $words).')/u', $text);
|
||||||
|
|
||||||
|
if ($assignedToCase && $has(['umbuchen', 'verschieb', 'stornieren', 'stornierung', 'später anreisen', 'früher anreisen', 'ändern'])) {
|
||||||
|
return MessageIntent::ChangeRequest;
|
||||||
|
}
|
||||||
|
if ($assignedToCase && $has(['ankunft', 'uhr', 'personen', 'kennzeichen', 'adresse', 'telefon', 'handynummer'])) {
|
||||||
|
return MessageIntent::ProvideData;
|
||||||
|
}
|
||||||
|
if ($assignedToCase) {
|
||||||
|
return MessageIntent::CaseReply;
|
||||||
|
}
|
||||||
|
if ($has(['frei', 'verfügbar', 'buchen', 'reservieren', 'anreise', 'zeitraum', 'vom \d'])) {
|
||||||
|
return MessageIntent::StayInquiry;
|
||||||
|
}
|
||||||
|
if ($has(['\?', 'hund', 'haustier', 'parkplatz', 'wlan', 'preis', 'kosten', 'wie weit', 'strand', 'ausstattung'])) {
|
||||||
|
return MessageIntent::GeneralQuestion;
|
||||||
|
}
|
||||||
|
|
||||||
|
return MessageIntent::Unclear;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication;
|
||||||
|
|
||||||
|
use App\Enums\Medium;
|
||||||
|
use App\Enums\MessageEffect;
|
||||||
|
use App\Enums\MessageIntent;
|
||||||
|
use App\Models\Booking;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the process core decided about a message (V2.1): intent, case (only if verified), the effects that apply and why.
|
||||||
|
*/
|
||||||
|
final readonly class MessageDecision
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param list<MessageEffect> $effects applied effects, in order
|
||||||
|
* @param list<string> $reasons plain-language explanation
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public Medium $medium,
|
||||||
|
public MessageIntent $intent,
|
||||||
|
public ?Booking $booking,
|
||||||
|
public array $effects,
|
||||||
|
public array $reasons,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function has(MessageEffect $effect): bool
|
||||||
|
{
|
||||||
|
return in_array($effect, $this->effects, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{medium: string, intent: string, booking_id: ?int, effects: list<string>, reasons: list<string>}
|
||||||
|
*/
|
||||||
|
public function toArray(): array
|
||||||
|
{
|
||||||
|
return ['medium' => $this->medium->value, 'intent' => $this->intent->value, 'booking_id' => $this->booking?->id,
|
||||||
|
'effects' => array_map(fn (MessageEffect $effect): string => $effect->value, $this->effects), 'reasons' => $this->reasons];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication;
|
||||||
|
|
||||||
|
use App\Actions\ReceiveInboundMessage;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Enums\MessageEffect;
|
||||||
|
use App\Enums\MessageIntent;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingTask;
|
||||||
|
use App\Models\InboundMessage;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Support\Settings;
|
||||||
|
use Illuminate\Database\UniqueConstraintViolationException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entry of messages from every medium except the e-mail inbox, which keeps its own path (V2.1, docs/…/02 §6):
|
||||||
|
* store once → assign deterministically (only a reference verified by the adapter, and not contradicted by the text) →
|
||||||
|
* classify → apply the effects the rules allow. A message never creates a case, reservation, offer or booking; what is
|
||||||
|
* unclear or contradictory goes to review. No answer is sent here.
|
||||||
|
*/
|
||||||
|
class MessageIntake
|
||||||
|
{
|
||||||
|
public function __construct(private CommunicationRules $rules, private IntentClassifier $classifier) {}
|
||||||
|
|
||||||
|
public function handle(IncomingMessage $incoming): MessageDecision
|
||||||
|
{
|
||||||
|
$key = $incoming->medium->value.':'.$incoming->externalId;
|
||||||
|
$existing = InboundMessage::query()->where('message_id', $key)->first();
|
||||||
|
if ($existing !== null) {
|
||||||
|
return $this->fromStored($existing, $incoming);
|
||||||
|
}
|
||||||
|
|
||||||
|
$reasons = [];
|
||||||
|
$booking = $this->assignedCase($incoming, $reasons);
|
||||||
|
$intent = $this->classifier->classify($incoming->text, $booking !== null);
|
||||||
|
$effects = $this->effectsFor($incoming, $intent, $booking, $reasons);
|
||||||
|
$decision = new MessageDecision($incoming->medium, $intent, $booking, $effects, $reasons);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$message = InboundMessage::query()->create([
|
||||||
|
'message_id' => $key,
|
||||||
|
'medium' => $incoming->medium->value,
|
||||||
|
'from_address' => mb_substr($incoming->sender, 0, 255),
|
||||||
|
'from_name' => $incoming->senderName,
|
||||||
|
'subject' => mb_substr(strtok($incoming->text, "\n") ?: '', 0, 120),
|
||||||
|
'body' => $incoming->text,
|
||||||
|
'received_at' => $incoming->receivedAt,
|
||||||
|
'test_mode' => ! Settings::isLive(),
|
||||||
|
'status' => $booking !== null && ! $decision->has(MessageEffect::Review) ? InboundMessage::ASSIGNED : InboundMessage::NEEDS_REVIEW,
|
||||||
|
'booking_id' => $booking?->id,
|
||||||
|
'match_reason' => $booking !== null ? 'verified_reference' : null,
|
||||||
|
'intent' => $intent->value,
|
||||||
|
'decision' => $decision->toArray(),
|
||||||
|
]);
|
||||||
|
} catch (UniqueConstraintViolationException) {
|
||||||
|
return $this->fromStored(InboundMessage::query()->where('message_id', $key)->firstOrFail(), $incoming);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->apply($message, $decision);
|
||||||
|
|
||||||
|
return $decision;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<string> $reasons
|
||||||
|
*/
|
||||||
|
private function assignedCase(IncomingMessage $incoming, array &$reasons): ?Booking
|
||||||
|
{
|
||||||
|
if ($incoming->verifiedBookingId === null) {
|
||||||
|
$reasons[] = 'Kein überprüfter Bezug zu einem Vorgang – Absender, Rufnummer, Name oder Zeitraum allein ordnen nicht zu.';
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$booking = Booking::query()->find($incoming->verifiedBookingId);
|
||||||
|
if ($booking === null) {
|
||||||
|
$reasons[] = 'Der überprüfte Bezug verweist auf keinen Vorgang dieses Vermieters.';
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (preg_match_all('/\b(20\d{2}-\d{4})\b/', $incoming->text, $numbers) && array_diff($numbers[1], [$booking->reference]) !== []) {
|
||||||
|
$reasons[] = 'Die Nachricht nennt eine andere Vorgangsnummer als der überprüfte Bezug – widersprüchlich.';
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$reasons[] = 'Dem Vorgang '.$booking->reference.' zugeordnet (überprüfter Bezug).';
|
||||||
|
|
||||||
|
return $booking;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<string> $reasons
|
||||||
|
* @return list<MessageEffect>
|
||||||
|
*/
|
||||||
|
private function effectsFor(IncomingMessage $incoming, MessageIntent $intent, ?Booking $booking, array &$reasons): array
|
||||||
|
{
|
||||||
|
if (! $this->rules->mediumActive($incoming->medium)) {
|
||||||
|
$reasons[] = $incoming->medium->getLabel().' ist für diesen Vermieter nicht eingeschaltet – die Nachricht liegt zur Klärung vor.';
|
||||||
|
|
||||||
|
return [MessageEffect::Review];
|
||||||
|
}
|
||||||
|
if ($this->rules->consentRequired($incoming->medium) && ! $incoming->consentGiven) {
|
||||||
|
$reasons[] = 'Für '.$incoming->medium->getLabel().' liegt keine Einwilligung vor – nur Klärung durch den Vermieter.';
|
||||||
|
|
||||||
|
return [MessageEffect::Review];
|
||||||
|
}
|
||||||
|
|
||||||
|
$effects = array_values(array_filter(
|
||||||
|
$this->rules->effects($incoming->medium, $intent),
|
||||||
|
fn (MessageEffect $effect): bool => ! $effect->needsCase() || $booking !== null,
|
||||||
|
));
|
||||||
|
// The review fallback only stands alone: where a real effect applies it is not added.
|
||||||
|
$real = array_values(array_filter($effects, fn (MessageEffect $effect): bool => $effect !== MessageEffect::Review));
|
||||||
|
if ($real === [] || $intent === MessageIntent::Unclear) {
|
||||||
|
$reasons[] = 'Nicht eindeutig oder nicht zulässig – zur Klärung vorgelegt, nichts wird übernommen.';
|
||||||
|
|
||||||
|
return [MessageEffect::Review];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $real;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function apply(InboundMessage $message, MessageDecision $decision): void
|
||||||
|
{
|
||||||
|
$booking = $decision->booking;
|
||||||
|
if ($booking === null || $decision->has(MessageEffect::Review)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
CaseLog::record($booking, 'message_in', $decision->medium->getLabel().'-Nachricht eingegangen ('.$decision->intent->getLabel().')', actor: CaseLog::GUEST, at: $message->received_at);
|
||||||
|
if ($decision->has(MessageEffect::ReportToCase) || $decision->has(MessageEffect::ContributeFacts)) {
|
||||||
|
BookingTask::openOnce($booking, BookingTaskKind::InboundReview, 'm'.$message->id, ['due_on' => today(), 'note' => $decision->medium->getLabel().'-Nachricht („'.mb_substr((string) $message->subject, 0, 100).'“) – im Posteingang ansehen; es wird nichts automatisch übernommen.']);
|
||||||
|
}
|
||||||
|
if ($decision->has(MessageEffect::ContributeFacts)) {
|
||||||
|
app(ReceiveInboundMessage::class)->evaluate($message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function fromStored(InboundMessage $stored, IncomingMessage $incoming): MessageDecision
|
||||||
|
{
|
||||||
|
$data = (array) $stored->decision;
|
||||||
|
|
||||||
|
return new MessageDecision(
|
||||||
|
$incoming->medium,
|
||||||
|
MessageIntent::tryFrom((string) $stored->intent) ?? MessageIntent::Unclear,
|
||||||
|
$stored->booking,
|
||||||
|
array_values(array_filter(array_map(fn (string $effect): ?MessageEffect => MessageEffect::tryFrom($effect), (array) ($data['effects'] ?? [])))),
|
||||||
|
(array) ($data['reasons'] ?? []),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Communication;
|
||||||
|
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingMessage;
|
||||||
|
use App\Models\InboundMessage;
|
||||||
|
use App\Models\Property;
|
||||||
|
use App\Support\Settings;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deterministic assignment of an incoming message to a case (v0.11, CH-07, CH-13) – no scoring. A message is
|
||||||
|
* assigned only by
|
||||||
|
*
|
||||||
|
* 1. a known reply reference (In-Reply-To / References of one of our mails),
|
||||||
|
* 2. our case number together with the case's guest as sender (the number alone is no proof of identity), or
|
||||||
|
* 3. the combination of sender (the guest's e-mail), property and both dates of exactly one open case of that guest.
|
||||||
|
*
|
||||||
|
* One open case of the same sender alone is not enough; it is only shown as a hint. Everything else waits in the inbox
|
||||||
|
* for the landlord. Being assigned does not yet allow taking anything over.
|
||||||
|
*/
|
||||||
|
class MessageMatcher
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array{booking: ?Booking, reason: ?string, hints: list<array{booking_id: int, reference: string, why: string}>}
|
||||||
|
*/
|
||||||
|
public function match(InboundMessage $message): array
|
||||||
|
{
|
||||||
|
$sender = mb_strtolower(trim((string) $message->from_address));
|
||||||
|
$text = $message->subject."\n".$message->body;
|
||||||
|
|
||||||
|
// Message-IDs are compared with and without angle brackets (mail servers deliver both forms).
|
||||||
|
$references = collect([$message->in_reply_to, ...((array) $message->references)])->filter()
|
||||||
|
->flatMap(fn (string $id): array => ['<'.trim($id, '<> ').'>', trim($id, '<> ')])->unique()->values()->all();
|
||||||
|
if ($references !== []) {
|
||||||
|
$replied = BookingMessage::query()->whereIn('message_id', $references)->whereNotNull('booking_id')->latest('id')->first()?->booking;
|
||||||
|
if ($replied !== null) {
|
||||||
|
return ['booking' => $replied, 'reason' => 'reply', 'hints' => []];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$hints = [];
|
||||||
|
// In test operation every answer comes from the test mailbox: there it stands for the guest of the named case.
|
||||||
|
$testSender = $message->test_mode && $sender !== '' && $sender === mb_strtolower(trim((string) Settings::tenant()?->test_recipient));
|
||||||
|
if (preg_match_all('/\b(20\d{2}-\d{4})\b/', $text, $numbers)) {
|
||||||
|
foreach (Booking::query()->whereIn('reference', array_unique($numbers[1]))->with('guest')->get() as $booking) {
|
||||||
|
if ($testSender) {
|
||||||
|
return ['booking' => $booking, 'reason' => 'reference_test_sender', 'hints' => []];
|
||||||
|
}
|
||||||
|
if ($sender !== '' && mb_strtolower((string) $booking->guest?->email) === $sender) {
|
||||||
|
return ['booking' => $booking, 'reason' => 'reference_and_sender', 'hints' => []];
|
||||||
|
}
|
||||||
|
$hints[] = ['booking_id' => $booking->id, 'reference' => $booking->reference, 'why' => 'Vorgangsnummer genannt, aber anderer Absender'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($sender === '') {
|
||||||
|
return ['booking' => null, 'reason' => null, 'hints' => $hints];
|
||||||
|
}
|
||||||
|
|
||||||
|
$open = Booking::query()
|
||||||
|
->whereHas('guest', fn ($guest) => $guest->where('email', $sender))
|
||||||
|
->whereNotIn('status', [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed])
|
||||||
|
->whereDate('departure', '>=', CarbonImmutable::today())
|
||||||
|
->with('property')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
$dates = $this->dates($text);
|
||||||
|
$singleProperty = Property::query()->count() === 1;
|
||||||
|
$candidates = $open->filter(fn (Booking $booking): bool => in_array($booking->arrival->toDateString(), $dates, true)
|
||||||
|
&& in_array($booking->departure->toDateString(), $dates, true)
|
||||||
|
&& ($singleProperty || mb_stripos($text, (string) $booking->property?->name) !== false));
|
||||||
|
|
||||||
|
if ($candidates->count() === 1) {
|
||||||
|
return ['booking' => $candidates->first(), 'reason' => 'sender_property_dates', 'hints' => []];
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($open as $booking) {
|
||||||
|
$hints[] = ['booking_id' => $booking->id, 'reference' => $booking->reference, 'why' => 'offener Vorgang dieses Absenders ('.$booking->arrival->format('d.m.').'–'.$booking->departure->format('d.m.Y').')'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['booking' => null, 'reason' => null, 'hints' => array_values(array_unique($hints, SORT_REGULAR))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dates written in the message (d.m.yyyy, d.m.yy, yyyy-mm-dd).
|
||||||
|
*
|
||||||
|
* @return list<string> Y-m-d
|
||||||
|
*/
|
||||||
|
public function dates(string $text): array
|
||||||
|
{
|
||||||
|
$dates = [];
|
||||||
|
if (preg_match_all('/\b(\d{1,2})\.\s?(\d{1,2})\.\s?(\d{4}|\d{2})\b/', $text, $german, PREG_SET_ORDER)) {
|
||||||
|
foreach ($german as [, $day, $month, $year]) {
|
||||||
|
$year = strlen($year) === 2 ? '20'.$year : $year;
|
||||||
|
if (checkdate((int) $month, (int) $day, (int) $year)) {
|
||||||
|
$dates[] = sprintf('%04d-%02d-%02d', $year, $month, $day);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (preg_match_all('/\b(20\d{2})-(\d{2})-(\d{2})\b/', $text, $iso, PREG_SET_ORDER)) {
|
||||||
|
foreach ($iso as [, $year, $month, $day]) {
|
||||||
|
if (checkdate((int) $month, (int) $day, (int) $year)) {
|
||||||
|
$dates[] = sprintf('%04d-%02d-%02d', $year, $month, $day);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values(array_unique($dates));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()->portals()->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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Process\ProcessRunner;
|
||||||
|
use App\Tenancy\TenantRunner;
|
||||||
|
use Illuminate\Console\Attributes\Description;
|
||||||
|
use Illuminate\Console\Attributes\Signature;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evaluates binding bookings that wait for an event again (V2.1, docs/Prozessarchitektur/V2.1/02 §5): the portal's
|
||||||
|
* confirmation mail did not come in time (escalate once), came meanwhile (close the escalation, go on) – without this nothing
|
||||||
|
* would resume or time out, because no scheduler looks at binding cases. Only cases whose channel makes them wait are
|
||||||
|
* touched; once per landlord.
|
||||||
|
*/
|
||||||
|
#[Signature('bookings:advance-waiting')]
|
||||||
|
#[Description('Re-evaluate binding bookings that wait for a portal confirmation (deadline, escalation, resume) – once per landlord')]
|
||||||
|
class AdvanceWaitingCases extends Command
|
||||||
|
{
|
||||||
|
public function handle(TenantRunner $tenants, ProcessRunner $runner): int
|
||||||
|
{
|
||||||
|
$tenants->each(function (Tenant $tenant) use ($runner): void {
|
||||||
|
$evaluated = 0;
|
||||||
|
Booking::query()->occupying()->where('intake', 'booking')->where('created_at', '>', now()->subDays(90))
|
||||||
|
->with(['property', 'guest', 'importChannel', 'originChannel'])
|
||||||
|
->each(function (Booking $booking) use ($runner, &$evaluated): void {
|
||||||
|
if (! $booking->process()->awaitsPortalConfirmation()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$runner->advance($booking, 'schedule:waiting');
|
||||||
|
$evaluated++;
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
report($exception);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->info("{$tenant->name}: {$evaluated} wartende Vorgang/Vorgänge bewertet.");
|
||||||
|
});
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Communication\Extraction\AiAccess;
|
||||||
|
use App\Communication\Extraction\ExtractionFailed;
|
||||||
|
use App\Communication\Extraction\MessageExtractor;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\InboundMessage;
|
||||||
|
use App\Models\Property;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use Illuminate\Console\Attributes\Description;
|
||||||
|
use Illuminate\Console\Attributes\Signature;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Measures the extraction on a set of anonymised sample messages (v0.11, M05): wrong values and missed details are
|
||||||
|
* counted separately – no system guarantees that it finds every detail, so the rate of missed ones is reported, not
|
||||||
|
* hidden. Calls the configured models (costs money); meant for calibrating prompts and thresholds before go-live.
|
||||||
|
*/
|
||||||
|
#[Signature('ai:evaluate {tenant : ID of the landlord whose own AI access is used} {--path= : JSON file with samples}')]
|
||||||
|
#[Description('Evaluate the guest message extraction against sample messages (wrong values and missed details)')]
|
||||||
|
class EvaluateExtraction extends Command
|
||||||
|
{
|
||||||
|
public function handle(MessageExtractor $extractor): int
|
||||||
|
{
|
||||||
|
$path = (string) ($this->option('path') ?: resource_path('prompts/extraction/evaluation/samples.json'));
|
||||||
|
// Bring your own key: the landlord's own access, as configured (System › KI-Anbindung).
|
||||||
|
$tenant = Tenant::query()->find((int) $this->argument('tenant'));
|
||||||
|
$service = $tenant === null ? null : AiAccess::service($tenant);
|
||||||
|
$access = $service === null ? null : AiAccess::fromService($service);
|
||||||
|
if ($access === null) {
|
||||||
|
$this->error('Für diesen Mandanten ist keine vollständige KI-Anbindung gespeichert.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$samples = (array) json_decode((string) file_get_contents($path), true);
|
||||||
|
$property = Property::query()->withoutGlobalScopes()->first() ?? new Property(['name' => 'Ferienwohnung', 'max_guests' => 4]);
|
||||||
|
$totals = ['expected' => 0, 'found' => 0, 'missed' => 0, 'wrong' => 0, 'extra' => 0, 'changes_missed' => 0, 'failed' => 0];
|
||||||
|
|
||||||
|
foreach ($samples as $sample) {
|
||||||
|
$booking = new Booking(['arrival' => now()->addDays(14)->toDateString(), 'departure' => now()->addDays(17)->toDateString(), 'guests' => 2, 'status' => 'reserved']);
|
||||||
|
$booking->setRelation('property', $property);
|
||||||
|
$booking->setRelation('guest', null);
|
||||||
|
$message = new InboundMessage(['subject' => $sample['subject'], 'body' => $sample['body']]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$result = $extractor->extract($access, $message, $booking)['data'];
|
||||||
|
} catch (ExtractionFailed $exception) {
|
||||||
|
$totals['failed']++;
|
||||||
|
$this->warn("{$sample['id']}: {$exception->getMessage()}");
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$found = collect($result['facts'])->mapWithKeys(fn (array $fact): array => [$fact['field'] => mb_strtolower(trim($fact['value']))])->all();
|
||||||
|
foreach ($sample['expected'] as $field => $value) {
|
||||||
|
$totals['expected']++;
|
||||||
|
match (true) {
|
||||||
|
! isset($found[$field]) => $totals['missed']++,
|
||||||
|
$found[$field] !== mb_strtolower($value) => $totals['wrong']++,
|
||||||
|
default => $totals['found']++,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
$totals['extra'] += count(array_diff_key($found, $sample['expected']));
|
||||||
|
$changes = collect($result['change_requests'])->pluck('field')->all();
|
||||||
|
$totals['changes_missed'] += count(array_diff($sample['expected_changes'], $changes));
|
||||||
|
$this->line("{$sample['id']}: ".json_encode(['found' => $found, 'changes' => $changes], JSON_UNESCAPED_UNICODE));
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->table(array_keys($totals), [array_values($totals)]);
|
||||||
|
$rate = $totals['expected'] > 0 ? round(100 * $totals['missed'] / $totals['expected'], 1) : 0;
|
||||||
|
$this->info("Übersehene Angaben: {$rate} % · Prompt-Version ".MessageExtractor::promptVersion());
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Actions\ExtractMessageFacts;
|
||||||
|
use App\Models\InboundMessage;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Tenancy\TenantRunner;
|
||||||
|
use Illuminate\Console\Attributes\Description;
|
||||||
|
use Illuminate\Console\Attributes\Signature;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
#[Signature('messages:extract')]
|
||||||
|
#[Description('Evaluate assigned guest and portal messages (v0.11 extraction) – a limited number per landlord and run')]
|
||||||
|
class ExtractInboundMessages extends Command
|
||||||
|
{
|
||||||
|
public function handle(ExtractMessageFacts $extract, TenantRunner $runner): int
|
||||||
|
{
|
||||||
|
$runner->each(function (Tenant $tenant) use ($extract): void {
|
||||||
|
$messages = InboundMessage::query()
|
||||||
|
->whereNotNull('booking_id')
|
||||||
|
->whereNull('extraction_status')
|
||||||
|
->whereIn('status', [InboundMessage::ASSIGNED, InboundMessage::PORTAL])
|
||||||
|
->orderBy('received_at')
|
||||||
|
->limit((int) config('fewo.ai.per_run', 10))
|
||||||
|
->get();
|
||||||
|
|
||||||
|
foreach ($messages as $message) {
|
||||||
|
try {
|
||||||
|
$this->line("{$tenant->name}: {$message->subject} → {$extract->handle($message)}");
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
report($exception);
|
||||||
|
$message->update(['extraction_status' => 'failed']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Console\Commands;
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
use App\Actions\ProcessPortalMail;
|
use App\Actions\ProcessPortalMail;
|
||||||
|
use App\Actions\ReceiveInboundMessage;
|
||||||
use App\Channels\ChannelSyncException;
|
use App\Channels\ChannelSyncException;
|
||||||
use App\Channels\Mail\MailboxReader;
|
use App\Channels\Mail\MailboxReader;
|
||||||
use App\Enums\TenantServiceKey;
|
use App\Enums\TenantServiceKey;
|
||||||
@@ -41,6 +42,27 @@ private function fetchForCurrentLandlord(MailboxReader $reader, ProcessPortalMai
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// v0.11: a dedicated mailbox is read completely; portal notifications still go through the portal path.
|
||||||
|
$mailbox = $tenant->activeMailbox();
|
||||||
|
if ($mailbox?->readsEverything()) {
|
||||||
|
try {
|
||||||
|
$mails = $reader->fetchAll();
|
||||||
|
} catch (ChannelSyncException $exception) {
|
||||||
|
$this->error("{$tenant->name}: {$exception->getMessage()}");
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
foreach ($mails as $mail) {
|
||||||
|
$message = app(ReceiveInboundMessage::class)->handle($mail, $mailbox);
|
||||||
|
if ($message->wasRecentlyCreated) {
|
||||||
|
$this->info("{$tenant->name}: {$message->statusLabel()} ({$message->subject})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$mailbox->forceFill(['last_fetched_at' => now()])->save();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
$senders = Channel::query()->active()->get()
|
$senders = Channel::query()->active()->get()
|
||||||
->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel))
|
->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel))
|
||||||
->unique()
|
->unique()
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Process\ProcessCatalogue;
|
||||||
|
use App\Process\ProcessPlan;
|
||||||
|
use Illuminate\Console\Attributes\Description;
|
||||||
|
use Illuminate\Console\Attributes\Signature;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks the process catalogue (docs/Prozessarchitektur/Architektur/05 §2.2) and, with --cases, that every frozen plan
|
||||||
|
* of every case (open or finished, every landlord) can still be read: model versions and module versions registered or
|
||||||
|
* declared compatible (requirement T3). With --matrix it writes MODULMATRIX.md.
|
||||||
|
*/
|
||||||
|
#[Signature('process:check {--cases : also check the frozen plans of all cases} {--matrix : write docs/Prozessarchitektur/Architektur/MODULMATRIX.md}')]
|
||||||
|
#[Description('Check the process catalogue (modules, models, dependencies, tester-only parts) and the frozen plans of the cases')]
|
||||||
|
class ProcessCheck extends Command
|
||||||
|
{
|
||||||
|
public function handle(ProcessCatalogue $catalogue): int
|
||||||
|
{
|
||||||
|
$problems = $catalogue->problems();
|
||||||
|
|
||||||
|
if ($this->option('cases')) {
|
||||||
|
$problems = [...$problems, ...$this->cases($catalogue)];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->option('matrix')) {
|
||||||
|
$path = base_path('docs/Prozessarchitektur/Architektur/MODULMATRIX.md');
|
||||||
|
file_put_contents($path, $this->matrix($catalogue));
|
||||||
|
$this->info('Modulmatrix geschrieben: '.$path);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($problems as $problem) {
|
||||||
|
$this->error($problem);
|
||||||
|
}
|
||||||
|
if ($problems === []) {
|
||||||
|
$this->info(count($catalogue->modules()).' Module, '.count($catalogue->modelVersions()).' Modelle: ohne Befund.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $problems === [] ? self::SUCCESS : self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
private function cases(ProcessCatalogue $catalogue): array
|
||||||
|
{
|
||||||
|
$problems = [];
|
||||||
|
Booking::withoutGlobalScopes()->select(['id', 'reference', 'profile', 'status'])->whereNotNull('profile')->lazyById()->each(function (Booking $booking) use ($catalogue, &$problems): void {
|
||||||
|
$plan = (array) (($booking->profile ?? [])['plan'] ?? []);
|
||||||
|
if ($plan === []) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$frozen = ProcessPlan::fromArray($plan);
|
||||||
|
if (! $catalogue->hasModel($frozen->model)) {
|
||||||
|
$problems[] = "Vorgang {$booking->reference}: Modell {$frozen->model} ist nicht mehr registriert.";
|
||||||
|
} elseif (! $catalogue->hasModel($frozen->model, $frozen->modelVersion)) {
|
||||||
|
$problems[] = "Vorgang {$booking->reference}: Modellversion {$frozen->reference()} fehlt im Register (T3: Versionen nicht entfernen, solange Vorgänge sie tragen).";
|
||||||
|
}
|
||||||
|
foreach ($frozen->modules as $key => $version) {
|
||||||
|
if (! $catalogue->serves($key, $version) && ! in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) {
|
||||||
|
$problems[] = "Offener Vorgang {$booking->reference}: Modul {$key}@{$version} wird nicht mehr bedient.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return $problems;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function matrix(ProcessCatalogue $catalogue): string
|
||||||
|
{
|
||||||
|
$models = $catalogue->models();
|
||||||
|
$lines = [
|
||||||
|
'# Modulmatrix (erzeugt)',
|
||||||
|
'',
|
||||||
|
'Erzeugt von `php artisan process:check --matrix` aus `config/process.php` – nicht von Hand ändern. Spalten: Modelle (Standardablauf; `V` = nur in einer Variante).',
|
||||||
|
'',
|
||||||
|
'| Modul | Version | Phase | Aktivierung | Verfügbarkeit | hart abhängig von | '.implode(' | ', array_keys($models)).' | Testgruppe |',
|
||||||
|
'|'.str_repeat('---|', 7 + count($models)),
|
||||||
|
];
|
||||||
|
foreach ($catalogue->modules() as $key => $class) {
|
||||||
|
$definition = $class::definition();
|
||||||
|
$cells = array_map(function ($model) use ($key): string {
|
||||||
|
if (in_array($key, $model->modules('standard'), true)) {
|
||||||
|
return '●';
|
||||||
|
}
|
||||||
|
foreach ($model->variants() as $variant) {
|
||||||
|
if (in_array($key, $model->modules($variant->key), true)) {
|
||||||
|
return 'V';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
|
}, $models);
|
||||||
|
$hard = implode(', ', array_map(fn ($dependency): string => $dependency->module, array_filter($definition->requires, fn ($dependency): bool => $dependency->hard)));
|
||||||
|
$lines[] = "| `{$key}` | {$class::version()} | {$definition->phase} | {$definition->toggle} | {$definition->availability} | {$hard} | ".implode(' | ', $cells)." | `module:{$key}` |";
|
||||||
|
}
|
||||||
|
|
||||||
|
return implode("\n", $lines)."\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Actions\RequestCaseData;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Tenancy\TenantRunner;
|
||||||
|
use Illuminate\Console\Attributes\Description;
|
||||||
|
use Illuminate\Console\Attributes\Signature;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
#[Signature('cases:data-requests')]
|
||||||
|
#[Description('Send due reminders of data requests and hand silent ones over to the landlord – once per landlord (v0.11)')]
|
||||||
|
class ProcessDataRequests extends Command
|
||||||
|
{
|
||||||
|
public function handle(RequestCaseData $requests, TenantRunner $runner): int
|
||||||
|
{
|
||||||
|
$runner->each(function (Tenant $tenant) use ($requests): void {
|
||||||
|
$count = $requests->remindDue();
|
||||||
|
|
||||||
|
$this->info("{$tenant->name}: {$count} Erinnerung(en) gesendet.");
|
||||||
|
});
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use Illuminate\Console\Attributes\Description;
|
||||||
|
use Illuminate\Console\Attributes\Signature;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checksums of what an update must never change by itself (docs/Prozessarchitektur/Architektur/06 U-F, step 6):
|
||||||
|
* the cases with their contract data and frozen profile, the channels' process configuration and the calendar blocks.
|
||||||
|
* Run before and after a deployment and compare. Only reads; prints no personal data.
|
||||||
|
*/
|
||||||
|
#[Signature('process:fingerprint')]
|
||||||
|
#[Description('Print checksums of cases, channel configurations and calendar blocks (compare before/after a deployment)')]
|
||||||
|
class ProcessFingerprint extends Command
|
||||||
|
{
|
||||||
|
public function handle(): int
|
||||||
|
{
|
||||||
|
$hash = fn ($query): string => md5($query->get()->map(fn (object $row): string => (string) json_encode($row))->implode("\n"));
|
||||||
|
|
||||||
|
$this->line((string) json_encode([
|
||||||
|
'bookings' => DB::table('bookings')->count(),
|
||||||
|
'channels' => DB::table('channels')->count(),
|
||||||
|
'blocked_periods' => DB::table('blocked_periods')->count(),
|
||||||
|
'h_bookings' => $hash(DB::table('bookings')->orderBy('id')->select('id', 'status', 'profile', 'total', 'quote', 'offer_terms', 'acceptance', 'arrival', 'departure', 'hold_expires_at', 'deposit_due_on', 'balance_due_on')),
|
||||||
|
'h_overrides' => $hash(DB::table('channels')->orderBy('id')->select('id', 'process_overrides', 'booking_model', 'case_intake')),
|
||||||
|
'h_blocks' => $hash(DB::table('blocked_periods')->orderBy('id')->select('id', 'starts_on', 'ends_on', 'source', 'channel_id', 'linked_booking_id', 'deleted_at')),
|
||||||
|
], JSON_PRETTY_PRINT));
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Models\Channel;
|
||||||
|
use App\Process\Modules\ContributesToPrice;
|
||||||
|
use App\Process\Modules\RunsAutomatically;
|
||||||
|
use App\Process\ProcessCatalogue;
|
||||||
|
use Illuminate\Console\Attributes\Description;
|
||||||
|
use Illuminate\Console\Attributes\Signature;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Change impact of a module (docs/Prozessarchitektur/Architektur/05 §2): models and variants with their case types,
|
||||||
|
* extension points, dependent modules, parameters, whether it reads frozen contract data, the number of channels that
|
||||||
|
* chose an affected model (count only) and the test groups to run.
|
||||||
|
*/
|
||||||
|
#[Signature('process:impact {module : key of the module, e.g. offer.binding}')]
|
||||||
|
#[Description('Show which models, case types, dependent modules, channels and test groups a change of a process module affects')]
|
||||||
|
class ProcessImpact extends Command
|
||||||
|
{
|
||||||
|
public function handle(ProcessCatalogue $catalogue): int
|
||||||
|
{
|
||||||
|
$key = (string) $this->argument('module');
|
||||||
|
if (! $catalogue->hasModule($key)) {
|
||||||
|
$this->error("Unbekanntes Modul {$key}. Registriert: ".implode(', ', array_keys($catalogue->modules())));
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$class = $catalogue->modules()[$key];
|
||||||
|
$definition = $class::definition();
|
||||||
|
$uses = [];
|
||||||
|
foreach ($catalogue->models() as $modelKey => $model) {
|
||||||
|
foreach ($model->variants() as $variant) {
|
||||||
|
if (in_array($key, $model->modules($variant->key), true)) {
|
||||||
|
$uses[] = $modelKey.($variant->key === 'standard' ? '' : ':'.$variant->key).' ('.implode('/', array_map(fn ($type): string => strtoupper($type->value), $model::caseTypes())).')';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$dependents = array_keys(array_filter($catalogue->modules(), fn (string $other): bool => collect($other::definition()->requires)->contains(fn ($dependency): bool => $dependency->module === $key)));
|
||||||
|
$modelKeys = array_map(fn (string $use): string => explode(' ', explode(':', $use)[0])[0], $uses);
|
||||||
|
$channels = Channel::withoutGlobalScopes()->get(['process_overrides'])->filter(fn (Channel $channel): bool => collect((array) $channel->process_overrides)->contains(fn ($config): bool => in_array($config['model'] ?? null, $modelKeys, true)))->count();
|
||||||
|
|
||||||
|
$this->table(['', $key.' v'.$class::version()], [
|
||||||
|
['Aufgabe', $definition->purpose],
|
||||||
|
['Phase / Aktivierung', $definition->phase.' / '.$definition->toggle.' / '.$definition->availability],
|
||||||
|
['Modelle', implode(', ', $uses) ?: '–'],
|
||||||
|
['Erweiterungspunkte', implode(', ', $definition->points) ?: 'fester Platz im Modell'],
|
||||||
|
['Benötigt', implode(', ', array_map(fn ($dependency): string => $dependency->module.($dependency->hard ? ' (hart)' : ' (weich)'), $definition->requires)) ?: '–'],
|
||||||
|
['Benötigt von', implode(', ', $dependents) ?: '–'],
|
||||||
|
['Läuft automatisch', is_subclass_of($class, RunsAutomatically::class) ? 'ja, Auslöser: '.implode(', ', $definition->triggers) : 'nein'],
|
||||||
|
['Preisbeitrag', is_subclass_of($class, ContributesToPrice::class) ? 'ja (CasePricing, nur vor Verbindlichkeit)' : 'nein'],
|
||||||
|
['Wertet Vertragsdaten aus', $definition->readsContractData ? 'ja – Bestandsfall-Test Pflicht (--group=ongoing)' : 'nein'],
|
||||||
|
['Parameter', implode(', ', array_map(fn ($parameter): string => is_string($parameter) ? $parameter : $parameter->value, $definition->parameters)) ?: '–'],
|
||||||
|
['Kanäle mit gewähltem Modell', (string) $channels],
|
||||||
|
['Tests', "--group=module:{$key} --group=golden --group=ongoing --group=runner"],
|
||||||
|
]);
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Process\Tester\EffectLedger;
|
||||||
|
use App\Process\Tester\ProcessSandboxDriver;
|
||||||
|
use App\Process\Tester\SandboxBootstrapper;
|
||||||
|
use Illuminate\Console\Attributes\Description;
|
||||||
|
use Illuminate\Console\Attributes\Signature;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entry of a tester run – only inside the process ProcessSandbox starts for it (environment FEWO_SANDBOX_RUN, so the
|
||||||
|
* SandboxBootstrapper has turned the process into a sandbox before anything was resolved). Reads input.json of the run
|
||||||
|
* and writes report.json; never touches anything outside the run's directory.
|
||||||
|
*/
|
||||||
|
#[Signature('process:sandbox-run {run : id of the prepared run}')]
|
||||||
|
#[Description('Play a process tester scenario inside its isolated process (started by the process tester only)')]
|
||||||
|
class ProcessSandboxRun extends Command
|
||||||
|
{
|
||||||
|
public function handle(ProcessSandboxDriver $driver): int
|
||||||
|
{
|
||||||
|
if (! SandboxBootstrapper::active() || (string) getenv(SandboxBootstrapper::ENV) !== (string) $this->argument('run') || config('sandbox.run') !== $this->argument('run')) {
|
||||||
|
$this->error('Nur innerhalb eines vom Prozess-Tester gestarteten Laufs.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$directory = (string) config('sandbox.directory');
|
||||||
|
try {
|
||||||
|
$report = $driver->run((array) json_decode((string) file_get_contents($directory.'/input.json'), true));
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$report = ['aborted' => 'Lauf abgebrochen: '.class_basename($exception).': '.$exception->getMessage(), 'timeline' => [], 'violations' => EffectLedger::violations()];
|
||||||
|
}
|
||||||
|
file_put_contents($directory.'/report.json', json_encode($report, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use Illuminate\Console\Attributes\Description;
|
||||||
|
use Illuminate\Console\Attributes\Signature;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\Artisan;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the migrated, empty SQLite template of the process tester's databases (storage/app/sandbox/template.sqlite).
|
||||||
|
* Run at every deployment after the migrations; a run copies it instead of migrating. Touches only that file.
|
||||||
|
*/
|
||||||
|
#[Signature('process:sandbox-template')]
|
||||||
|
#[Description('Build the empty, migrated SQLite template for process tester runs')]
|
||||||
|
class ProcessSandboxTemplate extends Command
|
||||||
|
{
|
||||||
|
public function handle(): int
|
||||||
|
{
|
||||||
|
if (! extension_loaded('pdo_sqlite')) {
|
||||||
|
$this->warn('pdo_sqlite fehlt – der Prozess-Tester bleibt gesperrt.');
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
$directory = storage_path('app/sandbox');
|
||||||
|
@mkdir($directory.'/runs', 0775, true);
|
||||||
|
$file = $directory.'/template.building.sqlite';
|
||||||
|
@unlink($file);
|
||||||
|
touch($file);
|
||||||
|
|
||||||
|
config(['database.connections.sandbox_template' => ['driver' => 'sqlite', 'database' => $file, 'prefix' => '', 'foreign_key_constraints' => true]]);
|
||||||
|
// `migrate --database` switches the default connection of this process and does not switch it back.
|
||||||
|
$default = DB::getDefaultConnection();
|
||||||
|
try {
|
||||||
|
Artisan::call('migrate', ['--database' => 'sandbox_template', '--force' => true, '--no-interaction' => true]);
|
||||||
|
} finally {
|
||||||
|
DB::setDefaultConnection($default);
|
||||||
|
DB::purge('sandbox_template');
|
||||||
|
config(['database.connections.sandbox_template' => null]);
|
||||||
|
}
|
||||||
|
|
||||||
|
rename($file, $directory.'/template.sqlite');
|
||||||
|
$this->info('Vorlage erstellt: '.$directory.'/template.sqlite');
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Enums\IntakeKind;
|
||||||
|
use App\Enums\ProcessSetting;
|
||||||
|
use App\Models\Channel;
|
||||||
|
use App\Models\Property;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Tenancy\TenantRunner;
|
||||||
|
use Illuminate\Console\Attributes\Description;
|
||||||
|
use Illuminate\Console\Attributes\Signature;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
#[Signature('process:settings-report')]
|
||||||
|
#[Description('Show every landlord’s process defaults and all deviations of properties and channels (read only)')]
|
||||||
|
class ProcessSettingsReport extends Command
|
||||||
|
{
|
||||||
|
public function handle(TenantRunner $runner): int
|
||||||
|
{
|
||||||
|
$runner->each(function (Tenant $tenant): void {
|
||||||
|
$this->line('');
|
||||||
|
$this->info($tenant->name);
|
||||||
|
|
||||||
|
$defaults = (array) ($tenant->process_defaults ?? []);
|
||||||
|
foreach (ProcessSetting::cases() as $setting) {
|
||||||
|
if (! $setting->isLandlordSetting()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$value = $setting->normalize($defaults[$setting->value] ?? null);
|
||||||
|
$this->line(' Standard · '.$setting->question().' '.$setting->describe($value ?? $setting->default()).($value === null ? ' (Grundeinstellung)' : ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows = [];
|
||||||
|
foreach (Property::query()->orderBy('name')->get() as $property) {
|
||||||
|
foreach ((array) ($property->process_overrides ?? []) as $key => $value) {
|
||||||
|
$setting = ProcessSetting::tryFrom((string) $key);
|
||||||
|
if ($setting?->normalize($value) !== null) {
|
||||||
|
$rows[] = ['Wohnung '.$property->name, $setting->question(), $setting->describe($setting->normalize($value))];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach (Channel::query()->with('property')->orderBy('name')->get() as $channel) {
|
||||||
|
foreach ((array) ($channel->process_overrides ?? []) as $intake => $values) {
|
||||||
|
foreach ((array) $values as $key => $value) {
|
||||||
|
$setting = ProcessSetting::tryFrom((string) $key);
|
||||||
|
if ($setting?->normalize($value) !== null) {
|
||||||
|
$rows[] = ['Portal '.$channel->name.' ('.$channel->property?->name.', '.(IntakeKind::tryFrom((string) $intake)?->getLabel() ?? $intake).')', $setting->question(), $setting->describe($setting->normalize($value))];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows === [] ? $this->line(' Keine Abweichungen.') : $this->table(['Wo', 'Einstellung', 'Wert'], $rows);
|
||||||
|
});
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Actions\RecordPayment;
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Tenancy\TenantRunner;
|
||||||
|
use Illuminate\Console\Attributes\Description;
|
||||||
|
use Illuminate\Console\Attributes\Signature;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
#[Signature('cases:recheck-payment-status
|
||||||
|
{--apply : Wirklich korrigieren (ohne: nur Vorschau)}')]
|
||||||
|
#[Description('Zahlungsstatus bestehender Vorgänge nach der neuen Regel prüfen: nur Geld des Gastes auf unserem Konto zählt als „Anzahlung erhalten“/„Bezahlt“, nicht „laut Portal bezahlt“ (Vorschau, Korrektur nur mit --apply und mit Eintrag im Verlauf)')]
|
||||||
|
class RecheckPaymentStatus extends Command
|
||||||
|
{
|
||||||
|
public function handle(TenantRunner $runner): int
|
||||||
|
{
|
||||||
|
$apply = (bool) $this->option('apply');
|
||||||
|
$rows = [];
|
||||||
|
|
||||||
|
$succeeded = $runner->each(function (Tenant $tenant) use ($apply, &$rows): void {
|
||||||
|
$cases = Booking::query()->with(['payments', 'property', 'importChannel', 'originChannel'])
|
||||||
|
->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid])->get();
|
||||||
|
|
||||||
|
foreach ($cases as $booking) {
|
||||||
|
$target = RecordPayment::statusFor($booking);
|
||||||
|
if ($target === null || $target === $booking->status) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$rows[] = [$tenant->name, $booking->reference, $booking->status->getLabel(), $target->getLabel(), $apply ? 'korrigiert' : 'Vorschau'];
|
||||||
|
if ($apply) {
|
||||||
|
CaseLog::context(fn () => $booking->update(['status' => $target]), actor: CaseLog::SYSTEM, reason: 'Zahlungsstatus nach neuer Regel: „laut Portal bezahlt“ ist kein Eingang auf unserem Konto (cases:recheck-payment-status).');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if ($rows === []) {
|
||||||
|
$this->info('Kein Vorgang mit abweichendem Zahlungsstatus.');
|
||||||
|
} else {
|
||||||
|
$this->table(['Vermieter', 'Vorgang', 'bisher', 'nach neuer Regel', 'Ergebnis'], $rows);
|
||||||
|
if (! $apply) {
|
||||||
|
$this->comment('Nur Vorschau. Mit --apply werden die Status korrigiert und im Verlauf vermerkt.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($succeeded < $runner->tenants()->count()) {
|
||||||
|
$this->error('Für mindestens einen Vermieter ist die Prüfung fehlgeschlagen (siehe Log).');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,9 +4,9 @@
|
|||||||
|
|
||||||
use App\Actions\AutoOffer;
|
use App\Actions\AutoOffer;
|
||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
use App\Enums\OfferMode;
|
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
|
use App\Process\ProcessRunner;
|
||||||
use App\Tenancy\TenantRunner;
|
use App\Tenancy\TenantRunner;
|
||||||
use Illuminate\Console\Attributes\Description;
|
use Illuminate\Console\Attributes\Description;
|
||||||
use Illuminate\Console\Attributes\Signature;
|
use Illuminate\Console\Attributes\Signature;
|
||||||
@@ -20,21 +20,25 @@ class SendPendingAutoOffers extends Command
|
|||||||
/**
|
/**
|
||||||
* Execute the console command.
|
* Execute the console command.
|
||||||
*/
|
*/
|
||||||
public function handle(AutoOffer $autoOffer, TenantRunner $runner): int
|
public function handle(AutoOffer $autoOffer, TenantRunner $tenants, ProcessRunner $runner): int
|
||||||
{
|
{
|
||||||
$runner->each(function (Tenant $tenant) use ($autoOffer): void {
|
$tenants->each(function (Tenant $tenant) use ($autoOffer, $runner): void {
|
||||||
$pending = Booking::query()
|
$pending = Booking::query()
|
||||||
->where('status', BookingStatus::Reserved)
|
->where('status', BookingStatus::Reserved)
|
||||||
->where('offer_version', 0)
|
->where('offer_version', 0)
|
||||||
->where('hold_expires_at', '>', now())
|
->where('information_version', 0)
|
||||||
->whereHas('property', fn ($query) => $query->where('offer_mode', OfferMode::Automatic)->where('pre_reservation_enabled', true))
|
// Held requests while their hold runs; requests without a hold (information, package 7) for two weeks.
|
||||||
->with(['property', 'guest'])
|
->where(fn ($query) => $query->where('hold_expires_at', '>', now())->orWhere(fn ($open) => $open->whereNull('hold_expires_at')->where('created_at', '>', now()->subDays(14))))
|
||||||
->get();
|
->where(fn ($query) => $query->whereNull('intake')->orWhere('intake', 'inquiry'))
|
||||||
|
->with(['property', 'guest', 'importChannel', 'originChannel'])
|
||||||
|
->get()
|
||||||
|
->filter(fn (Booking $booking): bool => $autoOffer->applies($booking) && ($booking->isHoldActive() || ! $booking->process()->preReservation()));
|
||||||
|
|
||||||
$sent = 0;
|
$sent = 0;
|
||||||
foreach ($pending as $booking) {
|
foreach ($pending as $booking) {
|
||||||
try {
|
try {
|
||||||
$sent += $autoOffer->handle($booking) === [] ? 1 : 0;
|
$result = $runner->advance($booking, 'schedule:bookings:auto-offers');
|
||||||
|
$sent += $result->ran('offer.binding') || $result->ran('offer.information') ? 1 : 0;
|
||||||
} catch (Throwable) {
|
} catch (Throwable) {
|
||||||
// The request stays pending for the landlord; the next run tries again.
|
// The request stays pending for the landlord; the next run tries again.
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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'));
|
$this->line("Versandweg: {$mailer}".($mailer === 'smtp' ? ' ('.config('mail.mailers.smtp.host').':'.config('mail.mailers.smtp.port').')' : '').' · Absender: '.config('mail.from.address'));
|
||||||
if (filled($redirect)) {
|
if (filled($redirect)) {
|
||||||
$this->line("Umleitung aktiv: die Mail geht an {$redirect} statt an {$to}.");
|
$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') {
|
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).');
|
$this->warn('Versandweg "log": es wird nichts zugestellt. Zum echten Versand MAIL_MAILER=smtp und MAIL_PASSWORD setzen (docs/BETRIEB.md §5a).');
|
||||||
|
|||||||
@@ -106,10 +106,10 @@ private static function values(Booking $booking, array $propertyData): array
|
|||||||
'anreise_datum' => $booking->arrival->format('d.m.Y'),
|
'anreise_datum' => $booking->arrival->format('d.m.Y'),
|
||||||
'abreise_datum' => $booking->departure->format('d.m.Y'),
|
'abreise_datum' => $booking->departure->format('d.m.Y'),
|
||||||
'naechte' => (string) $booking->nights(),
|
'naechte' => (string) $booking->nights(),
|
||||||
'personen' => (string) $booking->guests,
|
'personen' => $booking->guests !== null ? (string) $booking->guests : null,
|
||||||
'gesamtpreis' => Money::format($booking->total),
|
'gesamtpreis' => $booking->total !== null ? Money::format($booking->total) : null,
|
||||||
'anzahlung' => Money::format($booking->deposit),
|
'anzahlung' => $booking->deposit !== null ? Money::format($booking->deposit) : null,
|
||||||
'restzahlung' => Money::format($booking->total - $booking->deposit),
|
'restzahlung' => $booking->total !== null && $booking->deposit !== null ? Money::format($booking->total - $booking->deposit) : null,
|
||||||
'restzahlung_faellig' => $booking->balance_due_on?->format('d.m.Y'),
|
'restzahlung_faellig' => $booking->balance_due_on?->format('d.m.Y'),
|
||||||
'buchungsnummer' => $booking->reference,
|
'buchungsnummer' => $booking->reference,
|
||||||
'datum' => ($booking->confirmed_at ?? $booking->offer_sent_at ?? now())->format('d.m.Y'),
|
'datum' => ($booking->confirmed_at ?? $booking->offer_sent_at ?? now())->format('d.m.Y'),
|
||||||
|
|||||||
@@ -0,0 +1,430 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Documents;
|
||||||
|
|
||||||
|
use App\Actions\SendInformation;
|
||||||
|
use App\Actions\SendOffer;
|
||||||
|
use App\Availability\AvailabilityChecker;
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\DocumentKind;
|
||||||
|
use App\Enums\InquiryAnswer;
|
||||||
|
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\CaseRequirements;
|
||||||
|
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);
|
||||||
|
|
||||||
|
$quoted = in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true);
|
||||||
|
if ($quoted) {
|
||||||
|
$findings = [...$findings, ...$this->prepareOffer($booking, $draft, $changes, $kind)];
|
||||||
|
}
|
||||||
|
|
||||||
|
$frozen = ! $quoted && ($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} (and the information
|
||||||
|
* of a request without a hold, {@see SendInformation}) will.
|
||||||
|
*
|
||||||
|
* @param array<string, mixed> $changes
|
||||||
|
* @return list<DocumentFinding>
|
||||||
|
*/
|
||||||
|
private function prepareOffer(Booking $booking, Booking $draft, array $changes, DocumentKind $kind = DocumentKind::Offer): array
|
||||||
|
{
|
||||||
|
$findings = [];
|
||||||
|
$information = $kind === DocumentKind::Information;
|
||||||
|
|
||||||
|
if (! in_array($booking->status, $information ? [BookingStatus::Reserved, BookingStatus::Expired] : [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
|
||||||
|
$findings[] = DocumentFinding::blocker('Für diesen Vorgang ist '.($information ? 'keine Auskunft' : '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.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($information) {
|
||||||
|
$draft->forceFill([
|
||||||
|
'information_valid_until' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()),
|
||||||
|
'information_version' => $booking->information_version + 1,
|
||||||
|
'offer_message' => $changes['offer_message'] ?? $booking->offer_message,
|
||||||
|
]);
|
||||||
|
$findings[] = DocumentFinding::info('Unverbindliche Auskunft: Der Zeitraum wird nicht reserviert, und der Gast kann nicht direkt annehmen. Fragt er die Buchung an, wird erneut geprüft.');
|
||||||
|
if ($booking->information_version > 0) {
|
||||||
|
$findings[] = DocumentFinding::info('Ersetzt Auskunft Version '.$booking->information_version.'; deren Link wird ungültig.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $findings;
|
||||||
|
}
|
||||||
|
|
||||||
|
$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()->inquiryAnswer() === InquiryAnswer::Information) {
|
||||||
|
$findings[] = DocumentFinding::confirm('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht; vorgesehen ist eine unverbindliche Auskunft. Ein Angebot mit Annahmelink reserviert den Zeitraum für diesen Vorgang trotzdem bis '.$draft->hold_expires_at->format('d.m.Y, H:i').' Uhr, und der Gast kann bis dahin verbindlich annehmen.', 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.');
|
||||||
|
}
|
||||||
|
// G2a (v0.11, E-032): an own binding offer needs the contracting party's name, e-mail, full address with country,
|
||||||
|
// the number of guests and the dates – a hard blocker, also by hand. The information "unter Vorbehalt" does not (B3).
|
||||||
|
if ($kind === DocumentKind::Offer && $draft->guest !== null && ($missing = CaseRequirements::blocker($draft, CaseRequirements::OFFER)) !== null) {
|
||||||
|
$findings[] = DocumentFinding::blocker($missing);
|
||||||
|
}
|
||||||
|
if (! in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true) && $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',
|
||||||
|
in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true) => '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'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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))));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 ?? []);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,10 +2,10 @@
|
|||||||
|
|
||||||
namespace App\Documents;
|
namespace App\Documents;
|
||||||
|
|
||||||
use App\Enums\ChannelBookingModel;
|
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
use App\Models\ContractAnnex;
|
use App\Models\ContractAnnex;
|
||||||
use App\Models\ContractTemplate;
|
use App\Models\ContractTemplate;
|
||||||
|
use App\Process\ProcessSettings;
|
||||||
use App\Support\Content;
|
use App\Support\Content;
|
||||||
use Filament\Forms\Components\RichEditor\RichContentRenderer;
|
use Filament\Forms\Components\RichEditor\RichContentRenderer;
|
||||||
use Illuminate\Support\HtmlString;
|
use Illuminate\Support\HtmlString;
|
||||||
@@ -56,16 +56,12 @@ public static function capture(?ContractTemplate $template = null, ?Booking $boo
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The contract template for a booking: chosen explicitly, else the portal's (for bookings that are binding at the
|
* The contract template for a case: chosen explicitly, else the one of its process settings – the channel's
|
||||||
* portal its reservation template, otherwise its offer template), else the property's.
|
* template for the case's intake kind (request or binding booking), else the property's, else the landlord's.
|
||||||
*/
|
*/
|
||||||
public static function templateFor(Booking $booking, int|string|null $explicitId = null): ?ContractTemplate
|
public static function templateFor(Booking $booking, int|string|null $explicitId = null): ?ContractTemplate
|
||||||
{
|
{
|
||||||
$channel = $booking->importChannel ?? $booking->originChannel;
|
$id = filled($explicitId) ? (int) $explicitId : app(ProcessSettings::class)->forBooking($booking)->contractTemplateId();
|
||||||
$portalId = $channel === null ? null : ($channel->booking_model === ChannelBookingModel::PortalBooking
|
|
||||||
? ($channel->contract_template_reservation_id ?? $channel->contract_template_id)
|
|
||||||
: $channel->contract_template_id);
|
|
||||||
$id = filled($explicitId) ? (int) $explicitId : ($portalId ?? $booking->property->contract_template_id);
|
|
||||||
|
|
||||||
return $id ? ContractTemplate::query()->find($id) : null;
|
return $id ? ContractTemplate::query()->find($id) : null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,50 +2,73 @@
|
|||||||
|
|
||||||
namespace App\Documents;
|
namespace App\Documents;
|
||||||
|
|
||||||
|
use App\Enums\DocumentKind;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
use App\Models\Site;
|
use App\Models\Site;
|
||||||
use Barryvdh\DomPDF\Facade\Pdf;
|
use Barryvdh\DomPDF\Facade\Pdf;
|
||||||
use Illuminate\Support\Facades\Storage;
|
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 PDF of a case's document. As a draft it is part of the offer (offer_path, one file per offer version); the
|
||||||
* the final contract is generated at confirmation (contract_path). Both are stored, so later changes of
|
* document of record – rental contract, booking documentation of a portal booking or stay confirmation, depending on
|
||||||
* texts or prices do not alter a document the guest already received.
|
* 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
|
class RentalContract
|
||||||
{
|
{
|
||||||
private const DISK = 'local';
|
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']);
|
$booking->loadMissing(['guest', 'property']);
|
||||||
|
$kind = $draft ? DocumentKind::Offer : ($kind ?? DocumentKind::forCase($booking) ?? DocumentKind::Confirmation);
|
||||||
$filename = $draft
|
$filename = $draft
|
||||||
? "contracts/Angebot-{$booking->reference}-v{$booking->offer_version}.pdf"
|
? "Angebot-{$booking->reference}-v{$booking->offer_version}.pdf"
|
||||||
: "contracts/Mietvertrag-{$booking->reference}.pdf";
|
: "{$kind->fileName()}-{$booking->reference}.pdf";
|
||||||
$path = "contracts/tenants/{$booking->tenant_id}/bookings/{$booking->id}/".basename($filename);
|
$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
|
// The document of record is never rewritten once stored (confirmation resends reuse it).
|
||||||
// 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).
|
|
||||||
if (! $draft && $booking->contract_path !== null && Storage::disk(self::DISK)->exists($booking->contract_path)) {
|
if (! $draft && $booking->contract_path !== null && Storage::disk(self::DISK)->exists($booking->contract_path)) {
|
||||||
return $booking->contract_path;
|
return $booking->contract_path;
|
||||||
}
|
}
|
||||||
|
|
||||||
$document = OfferTerms::document($booking);
|
$pdf = $this->render($booking, $kind, $draft);
|
||||||
$pdf = Pdf::loadView($document !== null ? 'pdf.contract-document' : 'pdf.contract', [
|
|
||||||
'booking' => $booking,
|
|
||||||
'draft' => $draft,
|
|
||||||
'logo' => $logo,
|
|
||||||
'document' => $document,
|
|
||||||
])->setPaper('a4')->output();
|
|
||||||
Storage::disk(self::DISK)->put($path, $pdf);
|
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)]);
|
$booking->update([$draft ? 'offer_path' : 'contract_path' => $path, $draft ? 'offer_pdf_sha256' : 'contract_pdf_sha256' => hash('sha256', $pdf)]);
|
||||||
|
|
||||||
return $path;
|
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
|
public function absolutePath(Booking $booking, bool $draft = false): ?string
|
||||||
{
|
{
|
||||||
$path = $draft ? $booking->offer_path : $booking->contract_path;
|
$path = $draft ? $booking->offer_path : $booking->contract_path;
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use Filament\Support\Contracts\HasColor;
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where an activity of a case stands (docs/Prozessarchitektur/Querschnitt/Gates_und_Nachweise.md: done by us, done
|
||||||
|
* externally, not applicable, open, contradictory) – plus "waiting" for somebody else and "later" for what is not due.
|
||||||
|
*/
|
||||||
|
enum ActivityState: string implements HasColor, HasLabel
|
||||||
|
{
|
||||||
|
case Done = 'done';
|
||||||
|
case External = 'external';
|
||||||
|
case Open = 'open';
|
||||||
|
case Problem = 'problem';
|
||||||
|
case Waiting = 'waiting';
|
||||||
|
case Later = 'later';
|
||||||
|
case NotApplicable = 'not_applicable';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Done => 'erledigt',
|
||||||
|
self::External => 'übernimmt das Portal',
|
||||||
|
self::Open => 'zu tun',
|
||||||
|
self::Problem => 'Problem',
|
||||||
|
self::Waiting => 'wartet',
|
||||||
|
self::Later => 'später',
|
||||||
|
self::NotApplicable => 'entfällt',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getColor(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Done, self::External => 'success',
|
||||||
|
self::Open => 'warning',
|
||||||
|
self::Problem => 'danger',
|
||||||
|
self::Waiting => 'info',
|
||||||
|
self::Later, self::NotApplicable => 'gray',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public function icon(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Done, self::External => '✓',
|
||||||
|
self::Open => '●',
|
||||||
|
self::Problem => '!',
|
||||||
|
self::Waiting => '…',
|
||||||
|
self::Later => '○',
|
||||||
|
self::NotApplicable => '–',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the landlord has to act.
|
||||||
|
*/
|
||||||
|
public function needsAction(): bool
|
||||||
|
{
|
||||||
|
return $this === self::Open || $this === self::Problem;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,14 +2,13 @@
|
|||||||
|
|
||||||
namespace App\Enums;
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use App\Filament\Pages\Dashboard;
|
||||||
use App\Filament\Pages\OccupancyCalendar;
|
use App\Filament\Pages\OccupancyCalendar;
|
||||||
use App\Filament\Pages\PricesAndOffers;
|
use App\Filament\Pages\PricesAndOffers;
|
||||||
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
|
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
|
||||||
use App\Filament\Resources\Bookings\BookingResource;
|
use App\Filament\Resources\Bookings\BookingResource;
|
||||||
use App\Filament\Resources\BookingTasks\BookingTaskResource;
|
use App\Filament\Resources\Channels\ChannelResource;
|
||||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
|
||||||
use App\Filament\Resources\Guests\GuestResource;
|
use App\Filament\Resources\Guests\GuestResource;
|
||||||
use App\Filament\Resources\InboxMessages\InboxMessageResource;
|
|
||||||
use Filament\Support\Contracts\HasDescription;
|
use Filament\Support\Contracts\HasDescription;
|
||||||
use Filament\Support\Contracts\HasLabel;
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
@@ -22,19 +21,19 @@ enum AdminMode: string implements HasDescription, HasLabel
|
|||||||
case Expert = 'expert';
|
case Expert = 'expert';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Menu entries of the simple mode: the few things needed every day: calendar, bookings with their file, tasks, mailbox, guests and prices.
|
* Menu entries of the simple mode: the start page with everything to do, calendar, cases, guests, blocked periods
|
||||||
|
* and prices. Tasks, portal tasks and the mailbox are part of the start page's work list.
|
||||||
*
|
*
|
||||||
* @var list<class-string>
|
* @var list<class-string>
|
||||||
*/
|
*/
|
||||||
public const SIMPLE_NAVIGATION = [
|
public const SIMPLE_NAVIGATION = [
|
||||||
|
Dashboard::class,
|
||||||
OccupancyCalendar::class,
|
OccupancyCalendar::class,
|
||||||
BookingResource::class,
|
BookingResource::class,
|
||||||
BookingTaskResource::class,
|
|
||||||
ChannelTaskResource::class,
|
|
||||||
InboxMessageResource::class,
|
|
||||||
GuestResource::class,
|
GuestResource::class,
|
||||||
BlockedPeriodResource::class,
|
BlockedPeriodResource::class,
|
||||||
PricesAndOffers::class,
|
PricesAndOffers::class,
|
||||||
|
ChannelResource::class,
|
||||||
];
|
];
|
||||||
|
|
||||||
public function getLabel(): string
|
public function getLabel(): string
|
||||||
@@ -48,7 +47,7 @@ public function getLabel(): string
|
|||||||
public function getDescription(): string
|
public function getDescription(): string
|
||||||
{
|
{
|
||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::Simple => 'Das Tägliche: Postfach, Anfragen, Buchungen und Verträge, Sperrzeiten, Preise & Angebote, Gäste, Kalenderabgleich (iCal), Portal-Aufgaben, Bewertungen, Fotos',
|
self::Simple => 'Das Tägliche: Start mit allem, was zu tun ist, Kalender, Vorgänge, Gäste, Sperrzeiten, Preise',
|
||||||
self::Expert => 'Alle Einstellungen: Preise, Angebote, Kalenderabgleich (iCal), Webseite, System',
|
self::Expert => 'Alle Einstellungen: Preise, Angebote, Kalenderabgleich (iCal), Webseite, System',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the guest of a binding booking gets a short booking information (without contract) from us (docs/
|
||||||
|
* Prozessarchitektur/V2.1/02 §4) – independent of the contract documentation, which stays with its own step.
|
||||||
|
*/
|
||||||
|
enum BookingNoticeMode: string implements HasLabel
|
||||||
|
{
|
||||||
|
case Off = 'off';
|
||||||
|
case Automatic = 'automatic';
|
||||||
|
case AutomaticUnlessPortalConfirmed = 'automatic_unless_portal_confirmed';
|
||||||
|
case Manual = 'manual';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Off => 'keine eigene Buchungsinformation',
|
||||||
|
self::Automatic => 'automatisch senden',
|
||||||
|
self::AutomaticUnlessPortalConfirmed => 'automatisch senden – außer das Portal hat nachweislich bestätigt',
|
||||||
|
self::Manual => 'von Hand senden',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isAutomatic(): bool
|
||||||
|
{
|
||||||
|
return in_array($this, [self::Automatic, self::AutomaticUnlessPortalConfirmed], true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,10 @@
|
|||||||
/**
|
/**
|
||||||
* What the landlord has to do about a booking. Payment tasks are created by the daily run; nothing is
|
* What the landlord has to do about a booking. Payment tasks are created by the daily run; nothing is
|
||||||
* sent to the guest until the landlord has checked the payment and chooses to send the mail.
|
* sent to the guest until the landlord has checked the payment and chooses to send the mail.
|
||||||
|
*
|
||||||
|
* Package 9 sorts every task into what it holds up: tasks of the stay ({@see self::blocksStay()}) keep the stay from
|
||||||
|
* being closed, commercial tasks ({@see self::isCommercial()}) keep the case from being settled, follow-ups hold up
|
||||||
|
* neither and simply stay on the case until they are done.
|
||||||
*/
|
*/
|
||||||
enum BookingTaskKind: string implements HasLabel
|
enum BookingTaskKind: string implements HasLabel
|
||||||
{
|
{
|
||||||
@@ -16,6 +20,22 @@ enum BookingTaskKind: string implements HasLabel
|
|||||||
case BalanceReminder = 'balance_reminder';
|
case BalanceReminder = 'balance_reminder';
|
||||||
case CancellationRequest = 'cancellation_request';
|
case CancellationRequest = 'cancellation_request';
|
||||||
case CancellationFee = 'cancellation_fee';
|
case CancellationFee = 'cancellation_fee';
|
||||||
|
case PortalCancellation = 'portal_cancellation';
|
||||||
|
case PortalCancellationReported = 'portal_cancel_reported';
|
||||||
|
case PortalChangeReported = 'portal_change_reported';
|
||||||
|
case PortalConfirmationMissing = 'portal_confirmation_missing';
|
||||||
|
case RefundCheck = 'refund_check';
|
||||||
|
case BookingWish = 'booking_wish';
|
||||||
|
case ArrivalDetails = 'arrival_details';
|
||||||
|
case Service = 'service';
|
||||||
|
case Issue = 'issue';
|
||||||
|
case FollowUp = 'follow_up';
|
||||||
|
case PayoutCheck = 'payout_check';
|
||||||
|
case OpenClaim = 'open_claim';
|
||||||
|
case FactConflict = 'fact_conflict';
|
||||||
|
case ChangeRequest = 'change_request';
|
||||||
|
case GuestUnresponsive = 'guest_unresponsive';
|
||||||
|
case InboundReview = 'inbound_review';
|
||||||
|
|
||||||
public function getLabel(): string
|
public function getLabel(): string
|
||||||
{
|
{
|
||||||
@@ -25,12 +45,57 @@ public function getLabel(): string
|
|||||||
self::BalanceReminder => 'Restzahlung überfällig – anmahnen',
|
self::BalanceReminder => 'Restzahlung überfällig – anmahnen',
|
||||||
self::CancellationRequest => 'Stornierungswunsch des Gastes',
|
self::CancellationRequest => 'Stornierungswunsch des Gastes',
|
||||||
self::CancellationFee => 'Stornokosten prüfen und abrechnen',
|
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::PortalConfirmationMissing => 'Bestätigungsmail des Portals fehlt – bitte beim Portal prüfen',
|
||||||
|
self::RefundCheck => 'Erstattung an den Gast prüfen',
|
||||||
|
self::BookingWish => 'Buchungswunsch bestätigen?',
|
||||||
|
self::ArrivalDetails => 'Anreisedaten beim Gast erfragen',
|
||||||
|
self::Service => 'Leistung vorbereiten',
|
||||||
|
self::Issue => 'Abweichung oder Problem klären',
|
||||||
|
self::FollowUp => 'Folgeaufgabe',
|
||||||
|
self::PayoutCheck => 'Auszahlung des Portals prüfen',
|
||||||
|
self::OpenClaim => 'Offenen Betrag nach der Abreise klären',
|
||||||
|
self::FactConflict => 'Abweichende Angabe des Gastes prüfen',
|
||||||
|
self::ChangeRequest => 'Änderungswunsch des Gastes prüfen',
|
||||||
|
self::GuestUnresponsive => 'Fehlende Angaben selbst beim Gast nachfragen',
|
||||||
|
self::InboundReview => 'Antwort des Gastes prüfen',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this is a payment reminder task (created by the daily run, settled by a payment or a reminder mail).
|
||||||
|
*/
|
||||||
public function isPayment(): bool
|
public function isPayment(): bool
|
||||||
{
|
{
|
||||||
return ! in_array($this, [self::CancellationRequest, self::CancellationFee], true);
|
return in_array($this, [self::DepositReminder, self::BalanceRequest, self::BalanceReminder], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether an open task of this kind keeps the stay from being closed (it belongs to the stay itself).
|
||||||
|
*/
|
||||||
|
public function blocksStay(): bool
|
||||||
|
{
|
||||||
|
return in_array($this, [self::Service, self::Issue, self::PortalChangeReported], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether an open task of this kind keeps the case from being commercially settled.
|
||||||
|
*/
|
||||||
|
public function isCommercial(): bool
|
||||||
|
{
|
||||||
|
return $this->isPayment() || in_array($this, [self::CancellationFee, self::RefundCheck, self::PayoutCheck, self::OpenClaim], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Kinds the landlord adds by hand on a case (several per case, each with its own title).
|
||||||
|
*
|
||||||
|
* @return list<self>
|
||||||
|
*/
|
||||||
|
public static function manual(): array
|
||||||
|
{
|
||||||
|
return [self::Service, self::Issue, self::FollowUp];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -44,7 +109,7 @@ public function reminder(): ?array
|
|||||||
self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'],
|
self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'],
|
||||||
self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'],
|
self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'],
|
||||||
self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'],
|
self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'],
|
||||||
self::CancellationRequest, self::CancellationFee => null,
|
default => null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use Filament\Support\Contracts\HasDescription;
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The business constellation of a case (docs/Prozessarchitektur/01_Buchungsarchetypen.md). It follows from the way
|
||||||
|
* the case came in and who handles what – not from the channel's name alone.
|
||||||
|
*/
|
||||||
|
enum CaseType: string implements HasDescription, HasLabel
|
||||||
|
{
|
||||||
|
/** Own website or own direct way (phone, e-mail): request, own offer, acceptance. */
|
||||||
|
case A1 = 'a1';
|
||||||
|
|
||||||
|
/** Non-binding request passed on by an intermediary; own offer like A1. */
|
||||||
|
case A2 = 'a2';
|
||||||
|
|
||||||
|
/** Binding external booking, everything else is handled by the landlord. */
|
||||||
|
case A3 = 'a3';
|
||||||
|
|
||||||
|
/** Binding external booking with split handling (e.g. the portal collects the payments). */
|
||||||
|
case A4 = 'a4';
|
||||||
|
|
||||||
|
/** Binding external booking the portal handles almost completely. */
|
||||||
|
case A5 = 'a5';
|
||||||
|
|
||||||
|
/** Own use, private stay, maintenance or another block. */
|
||||||
|
case A6 = 'a6';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::A1 => 'Eigene Anfrage',
|
||||||
|
self::A2 => 'Anfrage über ein Portal',
|
||||||
|
self::A3 => 'Portalbuchung, Abwicklung bei uns',
|
||||||
|
self::A4 => 'Portalbuchung, Zahlung über das Portal',
|
||||||
|
self::A5 => 'Portalbuchung, Abwicklung durch das Portal',
|
||||||
|
self::A6 => 'Eigene Nutzung / Sperre',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getDescription(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::A1 => 'Anfrage → Angebot → Annahme durch den Gast',
|
||||||
|
self::A2 => 'Anfrage aus einem Portal, Angebot und Vertrag von uns',
|
||||||
|
self::A3 => 'Beim Portal schon verbindlich; Unterlagen, Zahlung und Gastkontakt übernehmen wir',
|
||||||
|
self::A4 => 'Beim Portal schon verbindlich; Unterlagen von uns, das Geld zieht das Portal ein',
|
||||||
|
self::A5 => 'Beim Portal schon verbindlich; das Portal erledigt Vertrag und Zahlung',
|
||||||
|
self::A6 => 'Eigenbelegung, private Überlassung, Wartung oder sonstige Sperre',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isExternallyBinding(): bool
|
||||||
|
{
|
||||||
|
return in_array($this, [self::A3, self::A4, self::A5], true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 573 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user