Compare commits
56
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 |
No files matched your search
@@ -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();
|
||||||
|
|||||||
@@ -8,10 +8,12 @@
|
|||||||
use App\Documents\DocumentFinding;
|
use App\Documents\DocumentFinding;
|
||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
use App\Enums\DocumentKind;
|
use App\Enums\DocumentKind;
|
||||||
|
use App\Enums\InquiryAnswer;
|
||||||
use App\Enums\ProcessingMode;
|
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;
|
||||||
|
|
||||||
@@ -19,6 +21,9 @@
|
|||||||
* 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),
|
||||||
* the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed) and an
|
* the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed) and an
|
||||||
@@ -30,6 +35,7 @@ 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
|
||||||
@@ -44,15 +50,22 @@ public function blockers(Booking $booking): array
|
|||||||
{
|
{
|
||||||
$property = $booking->property;
|
$property = $booking->property;
|
||||||
$reasons = [];
|
$reasons = [];
|
||||||
|
$information = $booking->process()->inquiryAnswer() === InquiryAnswer::Information;
|
||||||
|
|
||||||
if (! $booking->process()->preReservation()) {
|
if ($information && ($booking->status !== BookingStatus::Reserved || $booking->information_version > 0)) {
|
||||||
$reasons[] = 'Anfragen reservieren den Zeitraum nicht (Einstellung „Vorreservierung“); 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.';
|
||||||
@@ -61,10 +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).';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Status, e-mail, dates and the missing reservation are checked above; the composition adds what concerns the document.
|
// Status, e-mail and dates are checked above; the composition adds what concerns the document.
|
||||||
$reasons = [...$reasons, ...app(DocumentComposer::class)->compose($booking, DocumentKind::Offer)->toConfirm(except: [DocumentFinding::HOLD_ZERO])];
|
$reasons = [...$reasons, ...app(DocumentComposer::class)->compose($booking, $information ? DocumentKind::Information : DocumentKind::Offer)->toConfirm(except: [DocumentFinding::HOLD_ZERO])];
|
||||||
|
|
||||||
return [...$reasons, ...$this->clearance->reasons($property, $booking->created_at)];
|
// 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)];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -76,7 +90,7 @@ public function handle(Booking $booking): array
|
|||||||
{
|
{
|
||||||
$booking->loadMissing(['property', 'guest']);
|
$booking->loadMissing(['property', 'guest']);
|
||||||
|
|
||||||
if ($booking->process()->preReservation()) {
|
if ($booking->process()->inquiryAnswer() === InquiryAnswer::Offer) {
|
||||||
$this->clearance->refresh($booking->property);
|
$this->clearance->refresh($booking->property);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +100,11 @@ public function handle(Booking $booking): array
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$this->sendOffer->handle($booking->fresh(), ['expected_version' => 0]);
|
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()];
|
||||||
@@ -95,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;
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
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\Process\CaseLog;
|
||||||
use App\Support\CancellationCost;
|
use App\Support\CancellationCost;
|
||||||
use App\Support\Money;
|
use App\Support\Money;
|
||||||
@@ -65,6 +66,11 @@ public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTa
|
|||||||
->whereIn('kind', [BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported])
|
->whereIn('kind', [BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported])
|
||||||
->where('status', BookingTaskStatus::Open)
|
->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);
|
$this->refundTask($booking);
|
||||||
|
|
||||||
@@ -79,6 +85,8 @@ 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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -4,7 +4,9 @@
|
|||||||
|
|
||||||
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\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;
|
||||||
@@ -15,7 +17,9 @@
|
|||||||
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\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;
|
||||||
@@ -77,9 +81,15 @@ 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 = app(ProcessSettings::class)->resolve($property, $originChannel, IntakeKind::Inquiry);
|
$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,
|
||||||
@@ -95,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' => $profile->preReservation() ? now()->addHours($profile->holdHours()) : 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);
|
||||||
}
|
}
|
||||||
@@ -157,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))]);
|
||||||
}
|
|
||||||
$booking->refresh();
|
|
||||||
}
|
}
|
||||||
|
$asked = $result->ran('guest.data_request') && $booking->openDataRequest()?->last_sent_at !== null;
|
||||||
|
$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.'];
|
||||||
@@ -175,7 +198,7 @@ private function sendMails(Booking $booking): void
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (! $offerSent && filled($booking->guest?->email)) {
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,9 +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\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;
|
||||||
@@ -79,6 +81,7 @@ public function handle(PortalMail $mail): ?PortalEmail
|
|||||||
|
|
||||||
// One intake for all channels (package 4): bookings, requests and cancellations reach their case.
|
// One intake for all channels (package 4): bookings, requests and cancellations reach their case.
|
||||||
rescue(fn () => $this->intake($channel, $parsed, $record));
|
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)));
|
||||||
@@ -91,6 +94,22 @@ 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
|
private function intake(Channel $channel, ParsedPortalMail $parsed, PortalEmail $record): void
|
||||||
{
|
{
|
||||||
$intake = app(PortalIntake::class);
|
$intake = app(PortalIntake::class);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
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\IntakeKind;
|
||||||
use App\Enums\ProcessingMode;
|
use App\Enums\ProcessingMode;
|
||||||
use App\Exceptions\ReservationException;
|
use App\Exceptions\ReservationException;
|
||||||
@@ -41,15 +42,13 @@ 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.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($booking->guest === null) {
|
if ($booking->guest === null && (blank($contact['first_name'] ?? null) || blank($contact['last_name'] ?? null))) {
|
||||||
if (blank($contact['first_name'] ?? null) || blank($contact['last_name'] ?? null)) {
|
throw new ReservationException('Bitte Vor- und Nachnamen des Gastes angeben.');
|
||||||
throw new ReservationException('Bitte Vor- und Nachnamen des Gastes angeben.');
|
|
||||||
}
|
|
||||||
$guest = Guest::query()->create([...array_filter($contact, fn ($value) => $value !== null), 'email' => $contact['email'] ?? '']);
|
|
||||||
$booking->update(['guest_id' => $guest->id]);
|
|
||||||
} else {
|
|
||||||
$booking->guest->update(array_filter($contact, fn ($value) => $value !== null));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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()])->save();
|
$booking->forceFill(['guest_confirmed_at' => $booking->guest_confirmed_at ?? now()])->save();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,17 +3,27 @@
|
|||||||
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\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 payment of a case with its kind (package 8): the guest paid us, the portal reports the guest paid it, the
|
* Records a payment of a case with its kind (package 8): the guest paid us, the portal reports the guest paid it, the
|
||||||
* portal paid out to us, or we refunded the guest. Only the guest's payments move the booking along
|
* portal paid out to us, or we refunded the guest. A refund is stored as a negative amount.
|
||||||
* (Bestätigt → Anzahlung erhalten → Bezahlt); 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
|
||||||
{
|
{
|
||||||
@@ -21,7 +31,7 @@ public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, P
|
|||||||
{
|
{
|
||||||
$amount = $kind === PaymentKind::Refund ? -abs($amount) : $amount;
|
$amount = $kind === PaymentKind::Refund ? -abs($amount) : $amount;
|
||||||
|
|
||||||
return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy, $kind, $source): Payment {
|
$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(),
|
||||||
@@ -34,27 +44,84 @@ public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, P
|
|||||||
|
|
||||||
$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,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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,8 @@
|
|||||||
use App\Enums\Responsibility;
|
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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -27,7 +29,10 @@ public function handle(): int
|
|||||||
->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()->guestMessages() === Responsibility::Landlord);
|
->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));
|
||||||
|
|||||||
@@ -49,6 +49,41 @@ public function automatically(Booking $booking): array
|
|||||||
return $this->send($booking, $composition, acknowledged: false, automatic: true) ? [] : ['Die Unterlagen konnten nicht versendet werden (siehe Postfach).'];
|
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.
|
* Sending by hand after the landlord saw the composition.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
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;
|
||||||
@@ -17,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
|
||||||
{
|
{
|
||||||
@@ -27,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
|
||||||
{
|
{
|
||||||
@@ -61,25 +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->process()->guestMessages() === Responsibility::Landlord
|
->filter(fn (Booking $booking): bool => $booking->process()->arrivalInfoSender() === Responsibility::Landlord
|
||||||
&& $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->process()->arrivalInfoDaysBefore())));
|
&& $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]));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,12 +14,14 @@
|
|||||||
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\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;
|
||||||
@@ -65,6 +67,11 @@ 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();
|
$toConfirm = app(DocumentComposer::class)->compose($booking, DocumentKind::Offer, $changes)->toConfirm();
|
||||||
if ($toConfirm !== [] && ! ($changes['acknowledged'] ?? false)) {
|
if ($toConfirm !== [] && ! ($changes['acknowledged'] ?? false)) {
|
||||||
throw new ReservationException('Bitte die Hinweise prüfen und ausdrücklich bestätigen: '.implode(' ', $toConfirm));
|
throw new ReservationException('Bitte die Hinweise prüfen und ausdrücklich bestätigen: '.implode(' ', $toConfirm));
|
||||||
@@ -111,6 +118,7 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
|
|||||||
'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->process()->holdHours()),
|
'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,
|
||||||
@@ -182,7 +190,8 @@ public function offerUrl(Booking $booking): string
|
|||||||
*/
|
*/
|
||||||
public function quoteFor(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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
use App\Models\Guest;
|
use App\Models\Guest;
|
||||||
use App\Models\Property;
|
use App\Models\Property;
|
||||||
use App\Pricing\PortalPrice;
|
use App\Pricing\PortalPrice;
|
||||||
use App\Process\CaseAutomation;
|
use App\Process\ProcessRunner;
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Illuminate\Support\Arr;
|
use Illuminate\Support\Arr;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -96,7 +96,9 @@ public function handle(Property $property, Channel $channel, CarbonImmutable $ar
|
|||||||
return $booking->refresh();
|
return $booking->refresh();
|
||||||
});
|
});
|
||||||
|
|
||||||
app(CaseAutomation::class)->advance($booking);
|
// 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();
|
return $booking->refresh();
|
||||||
}
|
}
|
||||||
@@ -109,7 +111,7 @@ public function handle(Property $property, Channel $channel, CarbonImmutable $ar
|
|||||||
*/
|
*/
|
||||||
private function checkEvidence(BlockedPeriod $evidence): ?Booking
|
private function checkEvidence(BlockedPeriod $evidence): ?Booking
|
||||||
{
|
{
|
||||||
if (! in_array($evidence->source, ['channel', 'email'], true) || $evidence->channel_id === null) {
|
if (! in_array($evidence->source, ['channel', 'email', 'api'], true) || $evidence->channel_id === null) {
|
||||||
throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.');
|
throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.');
|
||||||
}
|
}
|
||||||
if ($evidence->occupationKind() === OccupationKind::Block) {
|
if ($evidence->occupationKind() === OccupationKind::Block) {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
use App\Models\Channel;
|
use App\Models\Channel;
|
||||||
use App\Process\CaseAutomation;
|
use App\Process\CaseAutomation;
|
||||||
use App\Process\ProcessSettings;
|
use App\Process\ProcessSettings;
|
||||||
|
use App\Process\RequestHold;
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
@@ -41,8 +42,13 @@ public function handle(Channel $channel, CarbonImmutable $arrival, CarbonImmutab
|
|||||||
}
|
}
|
||||||
|
|
||||||
$profile = $this->settings->resolve($property, $channel, IntakeKind::Inquiry);
|
$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([
|
return $property->bookings()->create([
|
||||||
|
...RequestHold::for($draft, $profile),
|
||||||
'status' => BookingStatus::Reserved,
|
'status' => BookingStatus::Reserved,
|
||||||
'source' => 'portal',
|
'source' => 'portal',
|
||||||
'intake' => IntakeKind::Inquiry,
|
'intake' => IntakeKind::Inquiry,
|
||||||
@@ -50,7 +56,6 @@ public function handle(Channel $channel, CarbonImmutable $arrival, CarbonImmutab
|
|||||||
'portal_reference' => $reference,
|
'portal_reference' => $reference,
|
||||||
'arrival' => $arrival->toDateString(),
|
'arrival' => $arrival->toDateString(),
|
||||||
'departure' => $departure->toDateString(),
|
'departure' => $departure->toDateString(),
|
||||||
'hold_expires_at' => $profile->preReservation() ? now()->addHours($profile->holdHours()) : null,
|
|
||||||
'processing_mode' => $processingMode,
|
'processing_mode' => $processingMode,
|
||||||
'internal_notes' => $notes,
|
'internal_notes' => $notes,
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -65,7 +65,7 @@ public function evaluate(BlockedPeriod $block): IntakeDecision
|
|||||||
$channel = $block->channel;
|
$channel = $block->channel;
|
||||||
$reference = self::reference($block);
|
$reference = self::reference($block);
|
||||||
|
|
||||||
if ($channel === null || ! in_array($block->source, ['channel', 'email'], true)) {
|
if ($channel === null || ! in_array($block->source, ['channel', 'email', 'api'], true)) {
|
||||||
return new IntakeDecision(IntakeOutcome::Ignore, ['Kein importierter Portaleintrag.'], reference: $reference);
|
return new IntakeDecision(IntakeOutcome::Ignore, ['Kein importierter Portaleintrag.'], reference: $reference);
|
||||||
}
|
}
|
||||||
if ($block->trashed()) {
|
if ($block->trashed()) {
|
||||||
@@ -246,6 +246,15 @@ public function cancellationMail(Channel $channel, ParsedPortalMail $parsed, Por
|
|||||||
return $case;
|
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
|
* 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.
|
* cases; otherwise only recorded.
|
||||||
@@ -292,6 +301,11 @@ public static function reference(BlockedPeriod $block): ?string
|
|||||||
return trim((string) $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:')) {
|
if ($block->source === 'email' && str_starts_with((string) $block->external_uid, 'email:')) {
|
||||||
$reference = substr((string) $block->external_uid, 6);
|
$reference = substr((string) $block->external_uid, 6);
|
||||||
|
|
||||||
@@ -315,7 +329,7 @@ public function caseByReference(Channel $channel, string $reference): ?Booking
|
|||||||
}
|
}
|
||||||
|
|
||||||
$linked = $channel->blockedPeriods()->withTrashed()->whereNotNull('linked_booking_id')
|
$linked = $channel->blockedPeriods()->withTrashed()->whereNotNull('linked_booking_id')
|
||||||
->whereIn('external_uid', [$reference, 'email:'.$reference])->value('linked_booking_id');
|
->whereIn('external_uid', [$reference, 'email:'.$reference, 'api:'.$reference])->value('linked_booking_id');
|
||||||
|
|
||||||
return $linked !== null ? Booking::query()->find($linked) : null;
|
return $linked !== null ? Booking::query()->find($linked) : null;
|
||||||
}
|
}
|
||||||
@@ -346,6 +360,9 @@ private function certainty(BlockedPeriod $block, ?string $reference): ?string
|
|||||||
if ($block->source === 'email') {
|
if ($block->source === 'email') {
|
||||||
return $reference === null ? 'Buchungsmail ohne Buchungsnummer – ohne Nummer lässt sich ein späterer Kalendereintrag nicht sicher zuordnen.' : null;
|
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.
|
// 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) {
|
if ($block->occupation_kind === OccupationKind::Reservation && $block->reviewed_at !== null && $block->origin_channel_id === $block->channel_id) {
|
||||||
|
|||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,7 +39,7 @@ public function handle(TenantRunner $runner, PortalIntake $intake): int
|
|||||||
$firstTask = (int) ChannelTask::query()->withoutGlobalScopes()->max('id');
|
$firstTask = (int) ChannelTask::query()->withoutGlobalScopes()->max('id');
|
||||||
|
|
||||||
$succeeded = $runner->each(function (Tenant $tenant) use ($intake, $apply, &$report): void {
|
$succeeded = $runner->each(function (Tenant $tenant) use ($intake, $apply, &$report): void {
|
||||||
$channels = Channel::query()->when($this->option('channel'), fn ($query, $ids) => $query->whereKey($ids))->orderBy('id')->get();
|
$channels = Channel::query()->portals()->when($this->option('channel'), fn ($query, $ids) => $query->whereKey($ids))->orderBy('id')->get();
|
||||||
foreach ($channels as $channel) {
|
foreach ($channels as $channel) {
|
||||||
$entries = $channel->blockedPeriods()->whereIn('source', ['channel', 'email'])->whereNull('linked_booking_id')
|
$entries = $channel->blockedPeriods()->whereIn('source', ['channel', 'email'])->whereNull('linked_booking_id')
|
||||||
->where('is_representation', false)->whereDate('ends_on', '>', today())->orderBy('starts_on')->get();
|
->where('is_representation', false)->whereDate('ends_on', '>', today())->orderBy('starts_on')->get();
|
||||||
|
|||||||
@@ -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,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,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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
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;
|
||||||
@@ -19,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)
|
||||||
|
// Held requests while their hold runs; requests without a hold (information, package 7) for two weeks.
|
||||||
|
->where(fn ($query) => $query->where('hold_expires_at', '>', now())->orWhere(fn ($open) => $open->whereNull('hold_expires_at')->where('created_at', '>', now()->subDays(14))))
|
||||||
|
->where(fn ($query) => $query->whereNull('intake')->orWhere('intake', 'inquiry'))
|
||||||
->with(['property', 'guest', 'importChannel', 'originChannel'])
|
->with(['property', 'guest', 'importChannel', 'originChannel'])
|
||||||
->get()
|
->get()
|
||||||
->filter(fn (Booking $booking): bool => $autoOffer->applies($booking) && $booking->process()->preReservation());
|
->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.
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,12 @@
|
|||||||
|
|
||||||
namespace App\Documents;
|
namespace App\Documents;
|
||||||
|
|
||||||
|
use App\Actions\SendInformation;
|
||||||
use App\Actions\SendOffer;
|
use App\Actions\SendOffer;
|
||||||
use App\Availability\AvailabilityChecker;
|
use App\Availability\AvailabilityChecker;
|
||||||
use App\Enums\BookingStatus;
|
use App\Enums\BookingStatus;
|
||||||
use App\Enums\DocumentKind;
|
use App\Enums\DocumentKind;
|
||||||
|
use App\Enums\InquiryAnswer;
|
||||||
use App\Enums\IntakeKind;
|
use App\Enums\IntakeKind;
|
||||||
use App\Enums\ProcessSetting;
|
use App\Enums\ProcessSetting;
|
||||||
use App\Enums\Responsibility;
|
use App\Enums\Responsibility;
|
||||||
@@ -16,6 +18,7 @@
|
|||||||
use App\Pricing\QuoteException;
|
use App\Pricing\QuoteException;
|
||||||
use App\Pricing\StayRequest;
|
use App\Pricing\StayRequest;
|
||||||
use App\Process\CaseActivities;
|
use App\Process\CaseActivities;
|
||||||
|
use App\Process\CaseRequirements;
|
||||||
use App\Process\ProcessProfile;
|
use App\Process\ProcessProfile;
|
||||||
use App\Process\ProcessSettings;
|
use App\Process\ProcessSettings;
|
||||||
use App\Support\Money;
|
use App\Support\Money;
|
||||||
@@ -55,11 +58,12 @@ public function compose(Booking $booking, ?DocumentKind $kind = null, array $cha
|
|||||||
$draft = clone $booking;
|
$draft = clone $booking;
|
||||||
$draft->setRelation('guest', $booking->guest !== null ? (clone $booking->guest)->fill(self::guestChanges($changes)) : null);
|
$draft->setRelation('guest', $booking->guest !== null ? (clone $booking->guest)->fill(self::guestChanges($changes)) : null);
|
||||||
|
|
||||||
if ($kind === DocumentKind::Offer) {
|
$quoted = in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true);
|
||||||
$findings = [...$findings, ...$this->prepareOffer($booking, $draft, $changes)];
|
if ($quoted) {
|
||||||
|
$findings = [...$findings, ...$this->prepareOffer($booking, $draft, $changes, $kind)];
|
||||||
}
|
}
|
||||||
|
|
||||||
$frozen = $kind !== DocumentKind::Offer && ($booking->contract_path !== null || ($booking->offer_version > 0 && is_array($booking->offer_terms)));
|
$frozen = ! $quoted && ($booking->contract_path !== null || ($booking->offer_version > 0 && is_array($booking->offer_terms)));
|
||||||
$explicitTemplate = ! $frozen && filled($changes['contract_template_id'] ?? null);
|
$explicitTemplate = ! $frozen && filled($changes['contract_template_id'] ?? null);
|
||||||
$template = match (true) {
|
$template = match (true) {
|
||||||
$kind === DocumentKind::StayConfirmation => null,
|
$kind === DocumentKind::StayConfirmation => null,
|
||||||
@@ -99,17 +103,19 @@ public function compose(Booking $booking, ?DocumentKind $kind = null, array $cha
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Applies the offer adjustments to the copy and calculates its price exactly as {@see SendOffer} will.
|
* 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
|
* @param array<string, mixed> $changes
|
||||||
* @return list<DocumentFinding>
|
* @return list<DocumentFinding>
|
||||||
*/
|
*/
|
||||||
private function prepareOffer(Booking $booking, Booking $draft, array $changes): array
|
private function prepareOffer(Booking $booking, Booking $draft, array $changes, DocumentKind $kind = DocumentKind::Offer): array
|
||||||
{
|
{
|
||||||
$findings = [];
|
$findings = [];
|
||||||
|
$information = $kind === DocumentKind::Information;
|
||||||
|
|
||||||
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
|
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 kein Angebot mehr möglich ('.$booking->status->getLabel().').');
|
$findings[] = DocumentFinding::blocker('Für diesen Vorgang ist '.($information ? 'keine Auskunft' : 'kein Angebot').' mehr möglich ('.$booking->status->getLabel().').');
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -141,6 +147,20 @@ private function prepareOffer(Booking $booking, Booking $draft, array $changes):
|
|||||||
$findings[] = DocumentFinding::blocker('Bitte Anreise, Abreise und Personen angeben.');
|
$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([
|
$draft->forceFill([
|
||||||
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()),
|
'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_version' => $booking->offer_version + 1,
|
||||||
@@ -148,8 +168,8 @@ private function prepareOffer(Booking $booking, Booking $draft, array $changes):
|
|||||||
'offer_message' => $changes['offer_message'] ?? $booking->offer_message,
|
'offer_message' => $changes['offer_message'] ?? $booking->offer_message,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (! $booking->process()->preReservation()) {
|
if ($booking->process()->inquiryAnswer() === InquiryAnswer::Information) {
|
||||||
$findings[] = DocumentFinding::confirm('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht. Ein Angebot mit Annahmelink reserviert ihn trotzdem bis '.$draft->hold_expires_at->format('d.m.Y, H:i').' Uhr, und der Gast kann bis dahin verbindlich annehmen. Eine Auskunft ohne Reservierung gibt es erst in einem späteren Ausbauschritt.', DocumentFinding::HOLD_ZERO);
|
$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) {
|
if ($booking->offer_version > 0) {
|
||||||
$findings[] = DocumentFinding::info('Ersetzt Angebot Version '.$booking->offer_version.'; dessen Link wird ungültig.');
|
$findings[] = DocumentFinding::info('Ersetzt Angebot Version '.$booking->offer_version.'; dessen Link wird ungültig.');
|
||||||
@@ -176,7 +196,12 @@ private function commonFindings(Booking $booking, Booking $draft, DocumentKind $
|
|||||||
} elseif (blank($draft->guest->email)) {
|
} elseif (blank($draft->guest->email)) {
|
||||||
$findings[] = DocumentFinding::blocker('Die E-Mail-Adresse des Gastes fehlt.');
|
$findings[] = DocumentFinding::blocker('Die E-Mail-Adresse des Gastes fehlt.');
|
||||||
}
|
}
|
||||||
if ($kind !== DocumentKind::Offer && $booking->total === null) {
|
// 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.');
|
$findings[] = DocumentFinding::blocker($booking->intake === IntakeKind::Booking ? 'Der Gesamtpreis (laut Portal) fehlt.' : 'Der Preis fehlt.');
|
||||||
}
|
}
|
||||||
if ($booking->confirmation_sent_at !== null && $kind !== DocumentKind::Offer) {
|
if ($booking->confirmation_sent_at !== null && $kind !== DocumentKind::Offer) {
|
||||||
@@ -249,7 +274,7 @@ private function priceSource(Booking $booking, Booking $draft, DocumentKind $kin
|
|||||||
return match (true) {
|
return match (true) {
|
||||||
$draft->total === null => 'noch nicht bekannt',
|
$draft->total === null => 'noch nicht bekannt',
|
||||||
($draft->quote['source'] ?? null) === 'portal' => 'laut '.($booking->processChannel()?->name ?? 'Portal').' übernommen, nicht neu berechnet',
|
($draft->quote['source'] ?? null) === 'portal' => 'laut '.($booking->processChannel()?->name ?? 'Portal').' übernommen, nicht neu berechnet',
|
||||||
$kind === DocumentKind::Offer => 'aus Ihren Preisen berechnet',
|
in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true) => 'aus Ihren Preisen berechnet',
|
||||||
$booking->accepted_at !== null => 'wie im angenommenen Angebot',
|
$booking->accepted_at !== null => 'wie im angenommenen Angebot',
|
||||||
default => 'aus Ihren Preisen berechnet',
|
default => 'aus Ihren Preisen berechnet',
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
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\Channels\ChannelResource;
|
||||||
use App\Filament\Resources\Guests\GuestResource;
|
use App\Filament\Resources\Guests\GuestResource;
|
||||||
use Filament\Support\Contracts\HasDescription;
|
use Filament\Support\Contracts\HasDescription;
|
||||||
use Filament\Support\Contracts\HasLabel;
|
use Filament\Support\Contracts\HasLabel;
|
||||||
@@ -32,6 +33,7 @@ enum AdminMode: string implements HasDescription, HasLabel
|
|||||||
GuestResource::class,
|
GuestResource::class,
|
||||||
BlockedPeriodResource::class,
|
BlockedPeriodResource::class,
|
||||||
PricesAndOffers::class,
|
PricesAndOffers::class,
|
||||||
|
ChannelResource::class,
|
||||||
];
|
];
|
||||||
|
|
||||||
public function getLabel(): string
|
public function getLabel(): string
|
||||||
|
|||||||
@@ -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
|
||||||
{
|
{
|
||||||
@@ -19,7 +23,19 @@ enum BookingTaskKind: string implements HasLabel
|
|||||||
case PortalCancellation = 'portal_cancellation';
|
case PortalCancellation = 'portal_cancellation';
|
||||||
case PortalCancellationReported = 'portal_cancel_reported';
|
case PortalCancellationReported = 'portal_cancel_reported';
|
||||||
case PortalChangeReported = 'portal_change_reported';
|
case PortalChangeReported = 'portal_change_reported';
|
||||||
|
case PortalConfirmationMissing = 'portal_confirmation_missing';
|
||||||
case RefundCheck = 'refund_check';
|
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
|
||||||
{
|
{
|
||||||
@@ -32,13 +48,54 @@ public function getLabel(): string
|
|||||||
self::PortalCancellation => 'Stornierung im Portal veranlassen bzw. prüfen',
|
self::PortalCancellation => 'Stornierung im Portal veranlassen bzw. prüfen',
|
||||||
self::PortalCancellationReported => 'Das Portal meldet eine Stornierung – bitte prüfen',
|
self::PortalCancellationReported => 'Das Portal meldet eine Stornierung – bitte prüfen',
|
||||||
self::PortalChangeReported => 'Das Portal meldet eine Änderung – 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::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, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported, self::RefundCheck], 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];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -52,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, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported, self::RefundCheck => null,
|
default => null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What happens with the contract document of a booking that is binding (docs/Prozessarchitektur/V2.1/02 §4): creating
|
||||||
|
* and filing it is separate from sending it to the guest. `Follow` keeps the behaviour of V2: it goes out the way the case
|
||||||
|
* is processed (automatically or by the landlord's hand).
|
||||||
|
*/
|
||||||
|
enum ContractDelivery: string implements HasLabel
|
||||||
|
{
|
||||||
|
case Follow = 'follow';
|
||||||
|
case Automatic = 'automatic';
|
||||||
|
case Manual = 'manual';
|
||||||
|
case Internal = 'internal';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Follow => 'wie die übrige Bearbeitung',
|
||||||
|
self::Automatic => 'automatisch erstellen und an den Gast senden',
|
||||||
|
self::Manual => 'von Hand prüfen und senden',
|
||||||
|
self::Internal => 'erstellen und nur intern ablegen (nicht senden)',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The mode as the document step sees it: automatic when the case is processed automatically or the delivery says so. */
|
||||||
|
public function sendsAutomatically(ProcessingMode $processing): bool
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Follow => $processing === ProcessingMode::Automatic,
|
||||||
|
self::Automatic => true,
|
||||||
|
self::Manual, self::Internal => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How missing details are requested from the guest (v0.11, CH §1.6) – independent of whether offers go out
|
||||||
|
* automatically.
|
||||||
|
*/
|
||||||
|
enum DataRequestMode: string implements HasLabel
|
||||||
|
{
|
||||||
|
case Automatic = 'automatic';
|
||||||
|
case Approval = 'approval';
|
||||||
|
case Manual = 'manual';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Automatic => 'Automatisch beim Gast nachfragen',
|
||||||
|
self::Approval => 'Rückfrage vorbereiten, Sie geben den Versand frei',
|
||||||
|
self::Manual => 'Sie fragen selbst nach (Aufgabe mit Textvorschlag)',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,8 +9,8 @@
|
|||||||
* The kinds of documents a case can produce (UMSETZUNGSPLAN_v0.10 §5.4). Which one a case needs follows from its case
|
* The kinds of documents a case can produce (UMSETZUNGSPLAN_v0.10 §5.4). Which one a case needs follows from its case
|
||||||
* type, never from a choice of the landlord: a request gets a binding offer, a booking we made ourselves gets the
|
* type, never from a choice of the landlord: a request gets a binding offer, a booking we made ourselves gets the
|
||||||
* confirmation with the rental contract, a booking that is already binding on a portal gets the booking documentation
|
* confirmation with the rental contract, a booking that is already binding on a portal gets the booking documentation
|
||||||
* without an acceptance link (E-004). Information "unter Vorbehalt" (package 7) and the stay confirmation of A6
|
* without an acceptance link (E-004), a request without a hold gets the information "unter Vorbehalt" with the link to
|
||||||
* (package 6) are prepared as working drafts but cannot be sent yet.
|
* ask for the booking (package 7, E-026).
|
||||||
*/
|
*/
|
||||||
enum DocumentKind: string implements HasLabel
|
enum DocumentKind: string implements HasLabel
|
||||||
{
|
{
|
||||||
@@ -20,6 +20,7 @@ enum DocumentKind: string implements HasLabel
|
|||||||
case ExternalRecord = 'external_record';
|
case ExternalRecord = 'external_record';
|
||||||
case StayConfirmation = 'stay_confirmation';
|
case StayConfirmation = 'stay_confirmation';
|
||||||
case Internal = 'internal';
|
case Internal = 'internal';
|
||||||
|
case DataRequest = 'data_request';
|
||||||
|
|
||||||
public function getLabel(): string
|
public function getLabel(): string
|
||||||
{
|
{
|
||||||
@@ -30,6 +31,7 @@ public function getLabel(): string
|
|||||||
self::ExternalRecord => 'Buchungsunterlagen (beim Portal gebucht)',
|
self::ExternalRecord => 'Buchungsunterlagen (beim Portal gebucht)',
|
||||||
self::StayConfirmation => 'Aufenthaltsbestätigung (privat)',
|
self::StayConfirmation => 'Aufenthaltsbestätigung (privat)',
|
||||||
self::Internal => 'Nur intern, kein Dokument an Gäste',
|
self::Internal => 'Nur intern, kein Dokument an Gäste',
|
||||||
|
self::DataRequest => 'Rückfrage nach fehlenden Angaben',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,11 +42,12 @@ public function description(): string
|
|||||||
{
|
{
|
||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::Offer => 'Für Anfragen: Preis, Vertragsentwurf und ein Link, mit dem der Gast verbindlich annimmt.',
|
self::Offer => 'Für Anfragen: Preis, Vertragsentwurf und ein Link, mit dem der Gast verbindlich annimmt.',
|
||||||
self::Information => 'Für Anfragen ohne Reservierung: Preis und Verfügbarkeit ohne Zusage; der Gast kann die Buchung anfragen. Folgt mit Paket 7.',
|
self::Information => 'Für Anfragen ohne Reservierung: Preis und Verfügbarkeit zum Zeitpunkt der Prüfung, ohne Reservierung und ohne Zusage. Der Gast kann daraus die Buchung anfragen; verbindlich wird sie erst mit Ihrer (oder der automatischen) Bestätigung nach erneuter Prüfung.',
|
||||||
self::Confirmation => 'Nach der Annahme eines Angebots oder einer direkt vereinbarten Buchung: Bestätigung mit dem Mietvertrag.',
|
self::Confirmation => 'Nach der Annahme eines Angebots oder einer direkt vereinbarten Buchung: Bestätigung mit dem Mietvertrag.',
|
||||||
self::ExternalRecord => 'Für Buchungen, die beim Portal bereits verbindlich sind: Buchungsdaten und – falls hinterlegt – Ihre Vorlage, ohne erneute Annahme durch den Gast.',
|
self::ExternalRecord => 'Für Buchungen, die beim Portal bereits verbindlich sind: Buchungsdaten und – falls hinterlegt – Ihre Vorlage, ohne erneute Annahme durch den Gast.',
|
||||||
self::StayConfirmation => 'Für private Überlassungen (Familie, Freunde): Bestätigung des Aufenthalts ohne Mietvertrag, nur auf Wunsch.',
|
self::StayConfirmation => 'Für private Überlassungen (Familie, Freunde): Bestätigung des Aufenthalts ohne Mietvertrag, nur auf Wunsch.',
|
||||||
self::Internal => 'Eigennutzung und Wartung: kein Dokument an Gäste.',
|
self::Internal => 'Eigennutzung und Wartung: kein Dokument an Gäste.',
|
||||||
|
self::DataRequest => 'E-Mail an den Gast mit der Bitte um fehlende Angaben (Anschrift, Personenzahl …) und einem persönlichen Link zum Ergänzen, dazu Erinnerungen und gezielte Folgefragen. Sie nennt nur eine tatsächlich bestehende vorläufige Reservierung. Im Testbetrieb gehen die Texte auch ohne Freigabe hinaus (nur an die Testadresse).',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,6 +62,7 @@ public static function forCase(Booking $booking): ?self
|
|||||||
$booking->intake === IntakeKind::Internal => $booking->guest_id !== null ? self::StayConfirmation : self::Internal,
|
$booking->intake === IntakeKind::Internal => $booking->guest_id !== null ? self::StayConfirmation : self::Internal,
|
||||||
$booking->caseType()->isExternallyBinding() => $profile->documents() === Responsibility::Portal ? null : self::ExternalRecord,
|
$booking->caseType()->isExternallyBinding() => $profile->documents() === Responsibility::Portal ? null : self::ExternalRecord,
|
||||||
$booking->isBinding() => $profile->documents() === Responsibility::Portal ? null : self::Confirmation,
|
$booking->isBinding() => $profile->documents() === Responsibility::Portal ? null : self::Confirmation,
|
||||||
|
$profile->inquiryAnswer() === InquiryAnswer::Information => self::Information,
|
||||||
default => self::Offer,
|
default => self::Offer,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -84,7 +88,7 @@ public function containsContract(): bool
|
|||||||
*/
|
*/
|
||||||
public function isAvailable(): bool
|
public function isAvailable(): bool
|
||||||
{
|
{
|
||||||
return in_array($this, [self::Offer, self::Confirmation, self::ExternalRecord, self::StayConfirmation], true);
|
return in_array($this, [self::Offer, self::Information, self::Confirmation, self::ExternalRecord, self::StayConfirmation, self::DataRequest], true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -116,6 +120,7 @@ public function fileName(): string
|
|||||||
self::ExternalRecord => 'Buchungsunterlagen',
|
self::ExternalRecord => 'Buchungsunterlagen',
|
||||||
self::StayConfirmation => 'Aufenthaltsbestaetigung',
|
self::StayConfirmation => 'Aufenthaltsbestaetigung',
|
||||||
self::Internal => 'Intern',
|
self::Internal => 'Intern',
|
||||||
|
self::DataRequest => 'Rueckfrage',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The ways a task of the process may be fulfilled (docs/Prozessarchitektur/V2.1/02 §2). What is business-mandatory stays
|
||||||
|
* mandatory; the question is not „can I switch it off?“ but „which admissible ways do I have?“. A module names its ways,
|
||||||
|
* the process model narrows them for its archetype.
|
||||||
|
*/
|
||||||
|
enum Execution: string implements HasLabel
|
||||||
|
{
|
||||||
|
case Automatic = 'automatic';
|
||||||
|
case Approval = 'approval';
|
||||||
|
case Manual = 'manual';
|
||||||
|
case Portal = 'portal';
|
||||||
|
case ServiceProvider = 'service_provider';
|
||||||
|
case External = 'external';
|
||||||
|
case NotRequired = 'not_required';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Automatic => 'automatisch durch FewoPortal',
|
||||||
|
self::Approval => 'vorbereitet, nach Ihrer Freigabe',
|
||||||
|
self::Manual => 'von Ihnen von Hand',
|
||||||
|
self::Portal => 'durch das Portal',
|
||||||
|
self::ServiceProvider => 'durch einen Dienstleister',
|
||||||
|
self::External => 'bereits extern erledigt (mit Nachweis)',
|
||||||
|
self::NotRequired => 'nicht erforderlich',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a detail of a case came from (v0.11 common fact intake, S5).
|
||||||
|
*/
|
||||||
|
enum FactSource: string implements HasLabel
|
||||||
|
{
|
||||||
|
case WebsiteForm = 'website_form';
|
||||||
|
case GuestLink = 'guest_link';
|
||||||
|
case Email = 'email';
|
||||||
|
case PortalMail = 'portal_mail';
|
||||||
|
case Extraction = 'llm';
|
||||||
|
case Landlord = 'landlord';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::WebsiteForm => 'Anfrageformular der Webseite',
|
||||||
|
self::GuestLink => 'Gast über den Ergänzungslink',
|
||||||
|
self::Email => 'E-Mail des Gastes',
|
||||||
|
self::PortalMail => 'Portal-Mail',
|
||||||
|
self::Extraction => 'aus einer Nachricht erkannt (KI)',
|
||||||
|
self::Landlord => 'von Ihnen eingetragen',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The landlord's own entry is authoritative; every other source only completes or is put to the landlord.
|
||||||
|
*/
|
||||||
|
public function isAuthoritative(): bool
|
||||||
|
{
|
||||||
|
return $this === self::Landlord;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ enum InboxMessageKind: string implements HasColor, HasLabel
|
|||||||
case OfferMailFailed = 'offer_mail_failed';
|
case OfferMailFailed = 'offer_mail_failed';
|
||||||
case OfferRejected = 'offer_rejected';
|
case OfferRejected = 'offer_rejected';
|
||||||
case SyncFailed = 'sync_failed';
|
case SyncFailed = 'sync_failed';
|
||||||
|
case AiAccessRejected = 'ai_access_rejected';
|
||||||
|
|
||||||
public function getLabel(): string
|
public function getLabel(): string
|
||||||
{
|
{
|
||||||
@@ -24,6 +25,7 @@ public function getLabel(): string
|
|||||||
self::OfferMailFailed => 'Angebot nicht zugestellt',
|
self::OfferMailFailed => 'Angebot nicht zugestellt',
|
||||||
self::OfferRejected => 'Annahme abgewiesen',
|
self::OfferRejected => 'Annahme abgewiesen',
|
||||||
self::SyncFailed => 'Kalenderabgleich gestört',
|
self::SyncFailed => 'Kalenderabgleich gestört',
|
||||||
|
self::AiAccessRejected => 'KI-Anbindung abgelehnt',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,7 +33,7 @@ public function getColor(): string
|
|||||||
{
|
{
|
||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::ChannelConflict, self::SyncFailed => 'danger',
|
self::ChannelConflict, self::SyncFailed => 'danger',
|
||||||
self::ConfirmationFailed, self::OfferMailFailed, self::OfferRejected => 'warning',
|
self::ConfirmationFailed, self::OfferMailFailed, self::OfferRejected, self::AiAccessRejected => 'warning',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How a request is answered first: a non-binding information or a binding offer the guest can accept. Independent of the
|
||||||
|
* reservation strategy (ProcessSetting::PreReservation) – except that an information reserves nothing by definition.
|
||||||
|
*/
|
||||||
|
enum InquiryAnswer: string implements HasLabel
|
||||||
|
{
|
||||||
|
case Information = 'information';
|
||||||
|
case Offer = 'offer';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Information => 'Unverbindliche Auskunft',
|
||||||
|
self::Offer => 'Verbindliches Angebot',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The communication medium a message came through (V2.1). It says nothing about bindingness or business meaning.
|
||||||
|
* WhatsApp and Chat exist as test cases of the architecture; no provider is connected.
|
||||||
|
*/
|
||||||
|
enum Medium: string implements HasLabel
|
||||||
|
{
|
||||||
|
case Email = 'email';
|
||||||
|
case Form = 'form';
|
||||||
|
case WhatsApp = 'whatsapp';
|
||||||
|
case Chat = 'chat';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Email => 'E-Mail',
|
||||||
|
self::Form => 'Formular',
|
||||||
|
self::WhatsApp => 'WhatsApp',
|
||||||
|
self::Chat => 'Chat',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a message may cause (V2.1). No effect creates a case, a reservation, an offer or a booking.
|
||||||
|
*/
|
||||||
|
enum MessageEffect: string implements HasLabel
|
||||||
|
{
|
||||||
|
case AnswerInformation = 'answer_information';
|
||||||
|
case ContributeFacts = 'contribute_facts';
|
||||||
|
case ReportToCase = 'report_to_case';
|
||||||
|
case HandoffInquiry = 'handoff_inquiry';
|
||||||
|
case Review = 'review';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::AnswerInformation => 'allgemeine Auskunft geben',
|
||||||
|
self::ContributeFacts => 'Angaben für den Vorgang vorschlagen',
|
||||||
|
self::ReportToCase => 'Aufgabe am Vorgang anlegen',
|
||||||
|
self::HandoffInquiry => 'auf den Anfrageweg verweisen',
|
||||||
|
self::Review => 'zur Klärung vorlegen',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Effects that act on an existing case and therefore need a verified assignment. */
|
||||||
|
public function needsCase(): bool
|
||||||
|
{
|
||||||
|
return $this === self::ContributeFacts || $this === self::ReportToCase;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use App\Communication\IntentClassifier;
|
||||||
|
use Filament\Support\Contracts\HasLabel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a message wants (V2.1) – decided by the rules of {@see IntentClassifier}, independent of the medium.
|
||||||
|
*/
|
||||||
|
enum MessageIntent: string implements HasLabel
|
||||||
|
{
|
||||||
|
case GeneralQuestion = 'general_question';
|
||||||
|
case StayInquiry = 'stay_inquiry';
|
||||||
|
case CaseReply = 'case_reply';
|
||||||
|
case ProvideData = 'provide_data';
|
||||||
|
case ChangeRequest = 'change_request';
|
||||||
|
case Unclear = 'unclear';
|
||||||
|
|
||||||
|
public function getLabel(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::GeneralQuestion => 'allgemeine Frage',
|
||||||
|
self::StayInquiry => 'Anfrage zu einem Aufenthalt',
|
||||||
|
self::CaseReply => 'Antwort in einem Vorgang',
|
||||||
|
self::ProvideData => 'Angaben zu einem Vorgang',
|
||||||
|
self::ChangeRequest => 'Änderungswunsch',
|
||||||
|
self::Unclear => 'unklar',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,21 @@ enum ProcessSetting: string
|
|||||||
case GuestMessages = 'guest_messages';
|
case GuestMessages = 'guest_messages';
|
||||||
case ArrivalInfoDaysBefore = 'arrival_info_days_before';
|
case ArrivalInfoDaysBefore = 'arrival_info_days_before';
|
||||||
case ContractTemplate = 'contract_template_id';
|
case ContractTemplate = 'contract_template_id';
|
||||||
|
case ClarificationHoldAutoMinutes = 'clarification_hold_auto_minutes';
|
||||||
|
case ClarificationHoldManualMinutes = 'clarification_hold_manual_minutes';
|
||||||
|
case DataRequest = 'data_request_mode';
|
||||||
|
case DataRequestRemindersMax = 'data_request_reminders_max';
|
||||||
|
case DataRequestFollowupsMax = 'data_request_followups_max';
|
||||||
|
case DataRequestReminderHours = 'data_request_reminder_hours';
|
||||||
|
case GuestLinkValidDays = 'guest_link_valid_days';
|
||||||
|
case FormRequiresAddress = 'form_requires_address';
|
||||||
|
case ContractDelivery = 'contract_delivery';
|
||||||
|
case BookingNotice = 'booking_notice';
|
||||||
|
case AwaitPortalConfirmation = 'await_portal_confirmation';
|
||||||
|
case PortalConfirmationWaitHours = 'portal_confirmation_wait_hours';
|
||||||
|
case InquiryAnswer = 'inquiry_answer';
|
||||||
|
case ArrivalInfoSender = 'arrival_info_sender';
|
||||||
|
case ReviewRequestSender = 'review_request_sender';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Built-in default (the behaviour before any landlord setting existed).
|
* Built-in default (the behaviour before any landlord setting existed).
|
||||||
@@ -30,6 +45,20 @@ public function default(): string|int|bool|null
|
|||||||
self::Documents, self::Payments, self::GuestMessages => Responsibility::Landlord->value,
|
self::Documents, self::Payments, self::GuestMessages => Responsibility::Landlord->value,
|
||||||
self::ArrivalInfoDaysBefore => 3,
|
self::ArrivalInfoDaysBefore => 3,
|
||||||
self::ContractTemplate => null,
|
self::ContractTemplate => null,
|
||||||
|
self::ClarificationHoldAutoMinutes => 15,
|
||||||
|
self::ClarificationHoldManualMinutes => 180,
|
||||||
|
self::DataRequest => DataRequestMode::Approval->value,
|
||||||
|
self::DataRequestRemindersMax => 2,
|
||||||
|
self::DataRequestFollowupsMax => 2,
|
||||||
|
self::DataRequestReminderHours => 24,
|
||||||
|
self::GuestLinkValidDays => 14,
|
||||||
|
self::FormRequiresAddress => false,
|
||||||
|
self::ContractDelivery => ContractDelivery::Follow->value,
|
||||||
|
self::BookingNotice => BookingNoticeMode::Off->value,
|
||||||
|
self::AwaitPortalConfirmation => false,
|
||||||
|
self::PortalConfirmationWaitHours => 48,
|
||||||
|
// Not set: derived (ProcessSettings) – the answer from the reservation, the senders from guest_messages.
|
||||||
|
self::InquiryAnswer, self::ArrivalInfoSender, self::ReviewRequestSender => null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,12 +70,27 @@ public function question(): string
|
|||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::Processing => 'Wie sollen neue Vorgänge bearbeitet werden?',
|
self::Processing => 'Wie sollen neue Vorgänge bearbeitet werden?',
|
||||||
self::PreReservation => 'Soll eine Anfrage den Zeitraum im Kalender reservieren?',
|
self::PreReservation => 'Soll eine Anfrage den Zeitraum im Kalender reservieren?',
|
||||||
self::HoldHours => 'Wie lange gilt ein Angebot (und bleibt der Zeitraum reserviert)?',
|
self::HoldHours => 'Wie lange gilt ein Angebot bzw. eine unverbindliche Auskunft (mit Reservierung: so lange bleibt der Zeitraum reserviert)?',
|
||||||
self::Documents => 'Wer schickt dem Gast Vertrag bzw. Buchungsunterlagen?',
|
self::Documents => 'Wer schickt dem Gast Vertrag bzw. Buchungsunterlagen?',
|
||||||
self::Payments => 'Wer kümmert sich um die Zahlungen des Gastes?',
|
self::Payments => 'Wer kümmert sich um die Zahlungen des Gastes?',
|
||||||
self::GuestMessages => 'Wer schickt dem Gast Anreise-Informationen und die Bitte um eine Bewertung?',
|
self::GuestMessages => 'Wer schickt dem Gast Anreise-Informationen und die Bitte um eine Bewertung?',
|
||||||
self::ArrivalInfoDaysBefore => 'Wann gehen die Anreise-Informationen an den Gast?',
|
self::ArrivalInfoDaysBefore => 'Wann gehen die Anreise-Informationen an den Gast?',
|
||||||
self::ContractTemplate => 'Welche Vertragsvorlage wird verwendet?',
|
self::ContractTemplate => 'Welche Vertragsvorlage wird verwendet?',
|
||||||
|
self::ClarificationHoldAutoMinutes => 'Wie lange wird der Zeitraum einer unvollständigen Anfrage vorläufig reserviert, wenn automatisch nachgefragt wird (0 = gar nicht)?',
|
||||||
|
self::ClarificationHoldManualMinutes => 'Wie lange wird der Zeitraum einer unvollständigen Anfrage vorläufig reserviert, wenn Sie die Rückfrage freigeben oder selbst nachfragen (0 = gar nicht)?',
|
||||||
|
self::DataRequest => 'Wie wird nach fehlenden Angaben gefragt?',
|
||||||
|
self::DataRequestRemindersMax => 'Wie oft wird höchstens erinnert, wenn der Gast nicht antwortet?',
|
||||||
|
self::DataRequestFollowupsMax => 'Wie viele gezielte Folgefragen gehen höchstens hinaus, wenn eine Antwort unvollständig ist?',
|
||||||
|
self::DataRequestReminderHours => 'Nach wie vielen Stunden ohne Antwort wird erinnert?',
|
||||||
|
self::GuestLinkValidDays => 'Wie lange gilt der Link, über den der Gast Angaben ergänzt?',
|
||||||
|
self::FormRequiresAddress => 'Muss die vollständige Anschrift schon im Anfrageformular der Webseite angegeben werden?',
|
||||||
|
self::ContractDelivery => 'Was geschieht mit dem Vertragsdokument einer verbindlichen Buchung?',
|
||||||
|
self::BookingNotice => 'Bekommt der Gast von uns eine Buchungsinformation (ohne Vertrag)?',
|
||||||
|
self::AwaitPortalConfirmation => 'Sollen Unterlagen und Nachrichten erst nach der Bestätigungsmail des Portals gehen?',
|
||||||
|
self::PortalConfirmationWaitHours => 'Wie lange wird auf die Bestätigungsmail des Portals gewartet, bevor Sie benachrichtigt werden?',
|
||||||
|
self::InquiryAnswer => 'Womit wird eine Anfrage zuerst beantwortet?',
|
||||||
|
self::ArrivalInfoSender => 'Wer schickt dem Gast die Anreise-Informationen?',
|
||||||
|
self::ReviewRequestSender => 'Wer bittet den Gast nach dem Aufenthalt um eine Bewertung?',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,10 +102,13 @@ public function question(): string
|
|||||||
public function channelIntakes(): array
|
public function channelIntakes(): array
|
||||||
{
|
{
|
||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::Processing, self::Payments, self::GuestMessages, self::ContractTemplate => [IntakeKind::Inquiry, IntakeKind::Booking],
|
self::Processing, self::Payments, self::GuestMessages, self::ContractTemplate, self::ArrivalInfoSender, self::ReviewRequestSender => [IntakeKind::Inquiry, IntakeKind::Booking],
|
||||||
|
self::InquiryAnswer => [IntakeKind::Inquiry],
|
||||||
self::PreReservation, self::HoldHours => [IntakeKind::Inquiry],
|
self::PreReservation, self::HoldHours => [IntakeKind::Inquiry],
|
||||||
self::Documents => [IntakeKind::Booking],
|
self::Documents, self::ContractDelivery, self::BookingNotice, self::AwaitPortalConfirmation, self::PortalConfirmationWaitHours => [IntakeKind::Booking],
|
||||||
self::ArrivalInfoDaysBefore => [],
|
self::ArrivalInfoDaysBefore, self::GuestLinkValidDays => [],
|
||||||
|
self::ClarificationHoldAutoMinutes, self::ClarificationHoldManualMinutes, self::FormRequiresAddress => [IntakeKind::Inquiry],
|
||||||
|
self::DataRequest, self::DataRequestRemindersMax, self::DataRequestFollowupsMax, self::DataRequestReminderHours => [IntakeKind::Inquiry, IntakeKind::Booking],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,7 +117,7 @@ public function channelIntakes(): array
|
|||||||
*/
|
*/
|
||||||
public function isLandlordSetting(): bool
|
public function isLandlordSetting(): bool
|
||||||
{
|
{
|
||||||
return $this !== self::ContractTemplate;
|
return ! in_array($this, [self::ContractTemplate, self::InquiryAnswer], true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -84,9 +131,16 @@ public function normalize(mixed $value): string|int|bool|null
|
|||||||
|
|
||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::Processing => ($value instanceof ProcessingMode ? $value : ProcessingMode::tryFrom((string) $value))?->value,
|
self::Processing => ($value instanceof ProcessingMode ? $value : ProcessingMode::tryFrom((string) $value))?->value,
|
||||||
self::Documents, self::Payments, self::GuestMessages => ($value instanceof Responsibility ? $value : Responsibility::tryFrom((string) $value))?->value,
|
self::Documents, self::Payments, self::GuestMessages, self::ArrivalInfoSender, self::ReviewRequestSender => ($value instanceof Responsibility ? $value : Responsibility::tryFrom((string) $value))?->value,
|
||||||
self::PreReservation => filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE),
|
self::InquiryAnswer => ($value instanceof InquiryAnswer ? $value : InquiryAnswer::tryFrom((string) $value))?->value,
|
||||||
|
self::PreReservation, self::FormRequiresAddress, self::AwaitPortalConfirmation => is_bool($value) ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE),
|
||||||
self::HoldHours, self::ArrivalInfoDaysBefore, self::ContractTemplate => is_numeric($value) ? (int) $value : null,
|
self::HoldHours, self::ArrivalInfoDaysBefore, self::ContractTemplate => is_numeric($value) ? (int) $value : null,
|
||||||
|
self::DataRequest => ($value instanceof DataRequestMode ? $value : DataRequestMode::tryFrom((string) $value))?->value,
|
||||||
|
self::ContractDelivery => ($value instanceof ContractDelivery ? $value : ContractDelivery::tryFrom((string) $value))?->value,
|
||||||
|
self::BookingNotice => ($value instanceof BookingNoticeMode ? $value : BookingNoticeMode::tryFrom((string) $value))?->value,
|
||||||
|
// 0 is a value of its own: no clarification hold, no reminder, no follow-up question.
|
||||||
|
self::ClarificationHoldAutoMinutes, self::ClarificationHoldManualMinutes, self::DataRequestRemindersMax, self::DataRequestFollowupsMax => is_numeric($value) ? max(0, (int) $value) : null,
|
||||||
|
self::DataRequestReminderHours, self::GuestLinkValidDays, self::PortalConfirmationWaitHours => is_numeric($value) ? max(1, (int) $value) : null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,11 +151,23 @@ public function describe(string|int|bool|null $value): string
|
|||||||
{
|
{
|
||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::Processing => ProcessingMode::tryFrom((string) $value)?->getLabel() ?? '–',
|
self::Processing => ProcessingMode::tryFrom((string) $value)?->getLabel() ?? '–',
|
||||||
self::Documents, self::Payments, self::GuestMessages => Responsibility::tryFrom((string) $value)?->getLabel() ?? '–',
|
self::Documents, self::Payments, self::GuestMessages, self::ArrivalInfoSender, self::ReviewRequestSender => Responsibility::tryFrom((string) $value)?->getLabel() ?? '–',
|
||||||
|
self::InquiryAnswer => InquiryAnswer::tryFrom((string) $value)?->getLabel() ?? '–',
|
||||||
self::PreReservation => $value ? 'ja' : 'nein',
|
self::PreReservation => $value ? 'ja' : 'nein',
|
||||||
self::HoldHours => $value.' Stunden',
|
self::HoldHours => $value.' Stunden',
|
||||||
self::ArrivalInfoDaysBefore => $value.' Tage vor Anreise',
|
self::ArrivalInfoDaysBefore => $value.' Tage vor Anreise',
|
||||||
self::ContractTemplate => $value === null ? 'Texte der Webseite' : 'Vorlage Nr. '.$value,
|
self::ContractTemplate => $value === null ? 'Texte der Webseite' : 'Vorlage Nr. '.$value,
|
||||||
|
self::ClarificationHoldAutoMinutes, self::ClarificationHoldManualMinutes => (int) $value === 0 ? 'keine vorläufige Reservierung' : $value.' Minuten',
|
||||||
|
self::DataRequest => DataRequestMode::tryFrom((string) $value)?->getLabel() ?? '–',
|
||||||
|
self::DataRequestRemindersMax => (int) $value === 0 ? 'keine Erinnerung' : 'höchstens '.$value.' Erinnerung'.((int) $value === 1 ? '' : 'en'),
|
||||||
|
self::DataRequestFollowupsMax => (int) $value === 0 ? 'keine Folgefrage' : 'höchstens '.$value.' Folgefrage'.((int) $value === 1 ? '' : 'n'),
|
||||||
|
self::DataRequestReminderHours => 'nach '.$value.' Stunden',
|
||||||
|
self::GuestLinkValidDays => $value.' Tage',
|
||||||
|
self::FormRequiresAddress => $value ? 'ja, Pflichtangabe' : 'nein, kann nachgefragt werden',
|
||||||
|
self::ContractDelivery => ContractDelivery::tryFrom((string) $value)?->getLabel() ?? '–',
|
||||||
|
self::BookingNotice => BookingNoticeMode::tryFrom((string) $value)?->getLabel() ?? '–',
|
||||||
|
self::AwaitPortalConfirmation => $value ? 'ja, erst nach der Bestätigungsmail' : 'nein',
|
||||||
|
self::PortalConfirmationWaitHours => $value.' Stunden',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,7 +31,8 @@ public function description(): string
|
|||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::PortalSync => 'Belegungen der Portale über iCal einlesen und den eigenen Kalender als Feed anbieten.',
|
self::PortalSync => 'Belegungen der Portale über iCal einlesen und den eigenen Kalender als Feed anbieten.',
|
||||||
self::PortalMail => 'Buchungsmails der Portale aus dem Postfach lesen und Termine sofort sperren.',
|
self::PortalMail => 'Buchungsmails der Portale aus dem Postfach lesen und Termine sofort sperren.',
|
||||||
self::AiOffers, self::AiMarketing, self::AiGuestMail => 'Noch nicht gebaut.',
|
self::AiGuestMail => 'Antworten und Nachrichten der Gäste auswerten: erkannte Angaben (Anschrift, Telefon …) werden vorgeschlagen und nur nach festen Regeln übernommen; nichts Verbindliches entscheidet die KI.',
|
||||||
|
self::AiOffers, self::AiMarketing => 'Noch nicht gebaut.',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,8 +42,8 @@ public function description(): string
|
|||||||
public function isWired(): bool
|
public function isWired(): bool
|
||||||
{
|
{
|
||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::PortalSync, self::PortalMail => true,
|
self::PortalSync, self::PortalMail, self::AiGuestMail => true,
|
||||||
self::AiOffers, self::AiMarketing, self::AiGuestMail => false,
|
self::AiOffers, self::AiMarketing => false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,11 +53,12 @@ public function isWired(): bool
|
|||||||
*/
|
*/
|
||||||
public function enabledByDefault(): bool
|
public function enabledByDefault(): bool
|
||||||
{
|
{
|
||||||
return $this->isWired();
|
// The AI service sends guests' messages to an external provider: only after the operator switched it on.
|
||||||
|
return $this->isWired() && $this !== self::AiGuestMail;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whether the landlord's own API key is of any use. Nothing calls out yet, so no service has one.
|
* Whether the landlord's own API key is of any use (the guest communication extraction calls out).
|
||||||
*/
|
*/
|
||||||
public function usesApiKey(): bool
|
public function usesApiKey(): bool
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Events;
|
||||||
|
|
||||||
|
use App\Enums\FactSource;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Process\FactContribution;
|
||||||
|
use Illuminate\Foundation\Events\Dispatchable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Details arrived for a case and went through the common fact intake (after the commit). The data request of the
|
||||||
|
* case listens to stop reminders or to plan a follow-up question (CH-17).
|
||||||
|
*/
|
||||||
|
class CaseFactsContributed
|
||||||
|
{
|
||||||
|
use Dispatchable;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
public readonly Booking $booking,
|
||||||
|
public readonly FactContribution $contribution,
|
||||||
|
public readonly FactSource $source,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
use App\Enums\DocumentKind;
|
use App\Enums\DocumentKind;
|
||||||
use App\Mail\BookingConfirmed;
|
use App\Mail\BookingConfirmed;
|
||||||
use App\Mail\BookingDocumentation;
|
use App\Mail\BookingDocumentation;
|
||||||
|
use App\Mail\InformationSent;
|
||||||
use App\Mail\OfferMade;
|
use App\Mail\OfferMade;
|
||||||
use App\Mail\StayConfirmed;
|
use App\Mail\StayConfirmed;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
@@ -86,6 +87,7 @@ private static function mailPreview(DocumentComposition $composition): string
|
|||||||
try {
|
try {
|
||||||
return match ($composition->kind) {
|
return match ($composition->kind) {
|
||||||
DocumentKind::Offer => (new OfferMade($draft, '#'))->render(),
|
DocumentKind::Offer => (new OfferMade($draft, '#'))->render(),
|
||||||
|
DocumentKind::Information => (new InformationSent($draft, '#'))->render(),
|
||||||
DocumentKind::ExternalRecord => (new BookingDocumentation($draft))->render(),
|
DocumentKind::ExternalRecord => (new BookingDocumentation($draft))->render(),
|
||||||
DocumentKind::StayConfirmation => (new StayConfirmed($draft))->render(),
|
DocumentKind::StayConfirmation => (new StayConfirmed($draft))->render(),
|
||||||
default => (new BookingConfirmed($draft))->render(),
|
default => (new BookingConfirmed($draft))->render(),
|
||||||
@@ -100,7 +102,7 @@ private static function mailPreview(DocumentComposition $composition): string
|
|||||||
private static function documentPreview(DocumentComposition $composition): string
|
private static function documentPreview(DocumentComposition $composition): string
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
[$view, $data] = app(RentalContract::class)->view($composition->draft, $composition->kind, draft: $composition->kind === DocumentKind::Offer);
|
[$view, $data] = app(RentalContract::class)->view($composition->draft, $composition->kind, draft: in_array($composition->kind, [DocumentKind::Offer, DocumentKind::Information], true));
|
||||||
|
|
||||||
return view($view, $data)->render();
|
return view($view, $data)->render();
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
|
|||||||
@@ -2,6 +2,10 @@
|
|||||||
|
|
||||||
namespace App\Filament\Forms;
|
namespace App\Filament\Forms;
|
||||||
|
|
||||||
|
use App\Enums\BookingNoticeMode;
|
||||||
|
use App\Enums\ContractDelivery;
|
||||||
|
use App\Enums\DataRequestMode;
|
||||||
|
use App\Enums\InquiryAnswer;
|
||||||
use App\Enums\ProcessingMode;
|
use App\Enums\ProcessingMode;
|
||||||
use App\Enums\ProcessSetting;
|
use App\Enums\ProcessSetting;
|
||||||
use App\Enums\Responsibility;
|
use App\Enums\Responsibility;
|
||||||
@@ -34,13 +38,29 @@ public static function field(string $name, ProcessSetting $setting, string $inhe
|
|||||||
return (match ($setting) {
|
return (match ($setting) {
|
||||||
ProcessSetting::Processing => Select::make($name)->options(ProcessingMode::class)->placeholder($placeholder)
|
ProcessSetting::Processing => Select::make($name)->options(ProcessingMode::class)->placeholder($placeholder)
|
||||||
->helperText('Automatisch: Das System sendet Angebote bzw. Unterlagen selbst, sobald alle Angaben da sind. Sonst bereitet es alles vor und Sie geben frei.'),
|
->helperText('Automatisch: Das System sendet Angebote bzw. Unterlagen selbst, sobald alle Angaben da sind. Sonst bereitet es alles vor und Sie geben frei.'),
|
||||||
ProcessSetting::PreReservation => Select::make($name)->options(['1' => 'Ja – der Zeitraum ist bis zum Ablauf des Angebots reserviert', '0' => 'Nein – eine Anfrage reserviert nichts'])->placeholder($placeholder),
|
ProcessSetting::PreReservation => Select::make($name)->options(['1' => 'Ja – der Zeitraum ist bis zum Ablauf des Angebots reserviert', '0' => 'Nein – der Gast erhält eine unverbindliche Auskunft und kann daraus die Buchung anfragen (erneute Prüfung vor der Bestätigung)'])->placeholder($placeholder),
|
||||||
ProcessSetting::HoldHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder),
|
ProcessSetting::HoldHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder),
|
||||||
ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages => Select::make($name)->options([Responsibility::Landlord->value => Responsibility::Landlord->getLabel(), Responsibility::Portal->value => Responsibility::Portal->getLabel()])->placeholder($placeholder),
|
ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages, ProcessSetting::ArrivalInfoSender, ProcessSetting::ReviewRequestSender => Select::make($name)->options([Responsibility::Landlord->value => Responsibility::Landlord->getLabel(), Responsibility::Portal->value => Responsibility::Portal->getLabel()])->placeholder($placeholder),
|
||||||
|
ProcessSetting::InquiryAnswer => Select::make($name)->options(InquiryAnswer::class)->placeholder($placeholder),
|
||||||
ProcessSetting::ArrivalInfoDaysBefore => TextInput::make($name)->integer()->minValue(1)->maxValue(14)->suffix('Tage vor Anreise')->placeholder($placeholder),
|
ProcessSetting::ArrivalInfoDaysBefore => TextInput::make($name)->integer()->minValue(1)->maxValue(14)->suffix('Tage vor Anreise')->placeholder($placeholder),
|
||||||
ProcessSetting::ContractTemplate => Select::make($name)
|
ProcessSetting::ContractTemplate => Select::make($name)
|
||||||
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
|
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
|
||||||
->placeholder($placeholder),
|
->placeholder($placeholder),
|
||||||
|
ProcessSetting::ClarificationHoldAutoMinutes, ProcessSetting::ClarificationHoldManualMinutes => TextInput::make($name)->integer()->minValue(0)->maxValue(1440)->suffix('Minuten')->placeholder($placeholder)
|
||||||
|
->helperText('Nur für Anfragen, denen noch Angaben für ein Angebot fehlen, und nur wenn der Zeitraum frei ist. Endet von selbst und wird durch Rückfragen nicht verlängert. Die Reservierung eines Angebots bleibt davon unberührt.'),
|
||||||
|
ProcessSetting::DataRequest => Select::make($name)->options(DataRequestMode::class)->placeholder($placeholder)
|
||||||
|
->helperText('Unabhängig davon, ob Angebote automatisch hinausgehen.'),
|
||||||
|
ProcessSetting::DataRequestRemindersMax, ProcessSetting::DataRequestFollowupsMax => TextInput::make($name)->integer()->minValue(0)->maxValue(5)->placeholder($placeholder),
|
||||||
|
ProcessSetting::DataRequestReminderHours => TextInput::make($name)->integer()->minValue(1)->maxValue(336)->suffix('Stunden')->placeholder($placeholder),
|
||||||
|
ProcessSetting::GuestLinkValidDays => TextInput::make($name)->integer()->minValue(1)->maxValue(60)->suffix('Tage')->placeholder($placeholder),
|
||||||
|
ProcessSetting::ContractDelivery => Select::make($name)->options(ContractDelivery::class)->placeholder($placeholder)
|
||||||
|
->helperText('Erstellen und Ablegen sind vom Versand getrennt. Ein nur intern abgelegter Vertrag gilt nicht als gesendet. Gilt für extern verbindliche Buchungen, bei denen wir die Vertragsunterlagen übernehmen.'),
|
||||||
|
ProcessSetting::BookingNotice => Select::make($name)->options(BookingNoticeMode::class)->placeholder($placeholder)
|
||||||
|
->helperText('Eine kurze Information über die Buchung – unabhängig vom Vertrag. Das Portal bleibt für seine eigenen Nachrichten zuständig.'),
|
||||||
|
ProcessSetting::AwaitPortalConfirmation => Select::make($name)->options(['1' => 'Ja – Unterlagen und Nachrichten warten auf die Bestätigungsmail des Portals', '0' => 'Nein – sofort bearbeiten'])->placeholder($placeholder)
|
||||||
|
->helperText('Die Belegung ist von Anfang an gesichert; es wartet nur, was Sie hier einstellen. Bleibt die Mail aus, erhalten Sie eine Aufgabe.'),
|
||||||
|
ProcessSetting::PortalConfirmationWaitHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder),
|
||||||
|
ProcessSetting::FormRequiresAddress => Select::make($name)->options(['1' => 'Ja – ohne vollständige Anschrift kann nicht angefragt werden', '0' => 'Nein – fehlt sie, wird beim Gast nachgefragt'])->placeholder($placeholder),
|
||||||
})->label($setting->question());
|
})->label($setting->question());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,196 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Pages;
|
||||||
|
|
||||||
|
use App\Communication\Extraction\AiAccess;
|
||||||
|
use App\Communication\Extraction\AiProvider;
|
||||||
|
use App\Communication\Extraction\ExtractionFailed;
|
||||||
|
use App\Communication\Extraction\LlmClient;
|
||||||
|
use App\Enums\TenantServiceKey;
|
||||||
|
use App\Enums\UserRole;
|
||||||
|
use App\Filament\Concerns\FollowsAdminMode;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\TenantService;
|
||||||
|
use App\Support\Settings;
|
||||||
|
use App\Tenancy\TenantFeatures;
|
||||||
|
use BackedEnum;
|
||||||
|
use Filament\Actions\Action;
|
||||||
|
use Filament\Forms\Components\Select;
|
||||||
|
use Filament\Forms\Components\TextInput;
|
||||||
|
use Filament\Notifications\Notification;
|
||||||
|
use Filament\Pages\Page;
|
||||||
|
use Filament\Schemas\Components\Actions;
|
||||||
|
use Filament\Schemas\Components\EmbeddedSchema;
|
||||||
|
use Filament\Schemas\Components\Form;
|
||||||
|
use Filament\Schemas\Components\Section;
|
||||||
|
use Filament\Schemas\Components\Text;
|
||||||
|
use Filament\Schemas\Components\Utilities\Get;
|
||||||
|
use Filament\Schemas\Schema;
|
||||||
|
use Filament\Support\Icons\Heroicon;
|
||||||
|
use UnitEnum;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "KI-Anbindung" (v0.11, bring your own key): the landlord connects his own AI access for the evaluation of guest
|
||||||
|
* messages – provider (Anthropic or OpenRouter), key and the two models. The key is stored encrypted and never shown
|
||||||
|
* again; an empty field keeps it. A check sends a tiny test request to both models. The page only exists when the
|
||||||
|
* operator switched the service on for this landlord.
|
||||||
|
*/
|
||||||
|
class AiConnection extends Page
|
||||||
|
{
|
||||||
|
use FollowsAdminMode;
|
||||||
|
|
||||||
|
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSparkles;
|
||||||
|
|
||||||
|
protected static string|UnitEnum|null $navigationGroup = 'System';
|
||||||
|
|
||||||
|
protected static ?string $navigationLabel = 'KI-Anbindung';
|
||||||
|
|
||||||
|
protected static ?string $title = 'KI-Anbindung';
|
||||||
|
|
||||||
|
protected static ?string $slug = 'ki-anbindung';
|
||||||
|
|
||||||
|
protected static ?int $navigationSort = 3;
|
||||||
|
|
||||||
|
/** @var array<string, mixed> */
|
||||||
|
public array $data = [];
|
||||||
|
|
||||||
|
public static function canAccess(): bool
|
||||||
|
{
|
||||||
|
return (bool) auth()->user()?->hasRole(UserRole::Admin) && app(TenantFeatures::class)->enabled(TenantServiceKey::AiGuestMail);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function mount(): void
|
||||||
|
{
|
||||||
|
$settings = (array) $this->service()?->settings;
|
||||||
|
|
||||||
|
// The key is never put into the form.
|
||||||
|
$this->form->fill([
|
||||||
|
'provider' => $settings['provider'] ?? null,
|
||||||
|
'small_model' => $settings['small_model'] ?? null,
|
||||||
|
'review_model' => $settings['review_model'] ?? null,
|
||||||
|
'api_key' => null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function form(Schema $schema): Schema
|
||||||
|
{
|
||||||
|
return $schema
|
||||||
|
->statePath('data')
|
||||||
|
->components([
|
||||||
|
Section::make('Ihr Zugang')
|
||||||
|
->description('Die Auswertung von Gast-Nachrichten nutzt Ihren eigenen Zugang bei einem KI-Anbieter; die Kosten rechnet der Anbieter mit Ihnen ab. Nachrichten werden dafür an den Anbieter übermittelt – bitte Auftragsverarbeitung und Datenschutzhinweise beachten. Ohne gültigen Zugang bleibt jede Nachricht zur Prüfung im Posteingang.')
|
||||||
|
->columns(2)
|
||||||
|
->schema([
|
||||||
|
Select::make('provider')->label('Anbieter')->options(AiProvider::class)->required()->live(),
|
||||||
|
TextInput::make('api_key')->label('API-Schlüssel')->password()->autocomplete('new-password')->maxLength(500)
|
||||||
|
->placeholder(fn (): string => filled($this->service()?->api_key) ? 'gespeichert – leer lassen, um ihn zu behalten' : 'noch keiner gespeichert')
|
||||||
|
->helperText('Wird verschlüsselt gespeichert und nie wieder angezeigt.'),
|
||||||
|
TextInput::make('small_model')->label('Modell für die erste Auswertung (klein, günstig)')->required()->maxLength(150)
|
||||||
|
->helperText(fn (Get $get): string => self::provider($get('provider'))?->modelExamples() ?? 'Kennung des Modells beim Anbieter'),
|
||||||
|
TextInput::make('review_model')->label('Modell für die Prüfung unsicherer Fälle (groß)')->required()->maxLength(150)
|
||||||
|
->helperText('Wird nur gefragt, wenn eine Angabe widersprüchlich, unplausibel oder unsicher ist.'),
|
||||||
|
]),
|
||||||
|
Section::make('Stand')
|
||||||
|
->schema([Text::make(fn (): string => $this->checkSummary())]),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function content(Schema $schema): Schema
|
||||||
|
{
|
||||||
|
return $schema->components([
|
||||||
|
Form::make([EmbeddedSchema::make('form')])
|
||||||
|
->id('form')
|
||||||
|
->livewireSubmitHandler('save')
|
||||||
|
->footer([Actions::make([
|
||||||
|
Action::make('save')->label('Speichern')->submit('save'),
|
||||||
|
Action::make('check')->label('Verbindung prüfen')->color('gray')->icon(Heroicon::OutlinedSignal)->action(fn () => $this->check()),
|
||||||
|
Action::make('removeKey')->label('Schlüssel entfernen')->color('danger')->requiresConfirmation()
|
||||||
|
->modalDescription('Danach ist die automatische Auswertung aus, bis ein neuer Schlüssel gespeichert ist.')
|
||||||
|
->visible(fn (): bool => filled($this->service()?->api_key))
|
||||||
|
->action(fn () => $this->removeKey()),
|
||||||
|
])]),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function save(): void
|
||||||
|
{
|
||||||
|
$state = $this->form->getState();
|
||||||
|
$service = $this->service() ?? new TenantService(['tenant_id' => $this->tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true]);
|
||||||
|
$service->settings = ['provider' => self::provider($state['provider'])?->value, 'small_model' => trim((string) $state['small_model']), 'review_model' => trim((string) $state['review_model'])];
|
||||||
|
if (filled($state['api_key'] ?? null)) {
|
||||||
|
$service->api_key = trim((string) $state['api_key']);
|
||||||
|
}
|
||||||
|
// A changed access is checked again before it counts as rejected.
|
||||||
|
$service->forceFill(['check_status' => null, 'check_message' => null])->save();
|
||||||
|
$this->data['api_key'] = null;
|
||||||
|
|
||||||
|
Notification::make()->title('Gespeichert')->body(filled($service->api_key) ? 'Bitte „Verbindung prüfen“ ausführen.' : 'Ohne Schlüssel bleibt die Auswertung aus.')->success()->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends a minimal structured request to both models; the result is stored, the key never shown.
|
||||||
|
*/
|
||||||
|
public function check(): void
|
||||||
|
{
|
||||||
|
$service = $this->service();
|
||||||
|
$access = $service === null ? null : AiAccess::fromService($service);
|
||||||
|
if ($access === null) {
|
||||||
|
Notification::make()->title('Unvollständig')->body('Bitte Anbieter, Schlüssel und beide Modelle speichern.')->warning()->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$schema = ['type' => 'object', 'additionalProperties' => false, 'required' => ['ok'], 'properties' => ['ok' => ['type' => 'boolean']]];
|
||||||
|
try {
|
||||||
|
foreach ([$access->smallModel, $access->reviewModel] as $model) {
|
||||||
|
app(LlmClient::class)->structured($access, $model, 'Answer with {"ok": true}.', 'Test', $schema, 'low');
|
||||||
|
}
|
||||||
|
} catch (ExtractionFailed $exception) {
|
||||||
|
$service->forceFill(['check_status' => AiAccess::INVALID, 'check_message' => mb_substr($exception->getMessage(), 0, 500), 'checked_at' => now()])->save();
|
||||||
|
Notification::make()->title('Prüfung fehlgeschlagen')->body($exception->getMessage())->danger()->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$service->forceFill(['check_status' => AiAccess::OK, 'check_message' => null, 'checked_at' => now()])->save();
|
||||||
|
Notification::make()->title('Verbindung in Ordnung')->body('Beide Modelle antworten im erwarteten Format.')->success()->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function removeKey(): void
|
||||||
|
{
|
||||||
|
$this->service()?->forceFill(['api_key' => null, 'check_status' => null, 'check_message' => null, 'checked_at' => null])->save();
|
||||||
|
Notification::make()->title('Schlüssel entfernt')->success()->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function provider(mixed $value): ?AiProvider
|
||||||
|
{
|
||||||
|
return $value instanceof AiProvider ? $value : AiProvider::tryFrom((string) $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function checkSummary(): string
|
||||||
|
{
|
||||||
|
$service = $this->service();
|
||||||
|
if ($service === null || blank($service->api_key)) {
|
||||||
|
return 'Kein Zugang gespeichert – Nachrichten werden nicht automatisch ausgewertet.';
|
||||||
|
}
|
||||||
|
|
||||||
|
return match ($service->check_status) {
|
||||||
|
AiAccess::OK => 'Zuletzt erfolgreich geprüft am '.$service->checked_at?->format('d.m.Y, H:i').' Uhr.',
|
||||||
|
AiAccess::INVALID => 'Abgelehnt am '.$service->checked_at?->format('d.m.Y, H:i').' Uhr: '.$service->check_message.' Die automatische Auswertung ist aus.',
|
||||||
|
default => 'Gespeichert, noch nicht geprüft.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private function service(): ?TenantService
|
||||||
|
{
|
||||||
|
return AiAccess::service($this->tenant());
|
||||||
|
}
|
||||||
|
|
||||||
|
private function tenant(): Tenant
|
||||||
|
{
|
||||||
|
$tenant = Settings::tenant();
|
||||||
|
abort_if($tenant === null, 404);
|
||||||
|
|
||||||
|
return $tenant;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Filament\Pages;
|
namespace App\Filament\Pages;
|
||||||
|
|
||||||
|
use App\Enums\InquiryAnswer;
|
||||||
use App\Enums\IntakeKind;
|
use App\Enums\IntakeKind;
|
||||||
use App\Enums\ProcessSetting;
|
use App\Enums\ProcessSetting;
|
||||||
use App\Enums\UserRole;
|
use App\Enums\UserRole;
|
||||||
@@ -12,6 +13,7 @@
|
|||||||
use App\Models\Property;
|
use App\Models\Property;
|
||||||
use App\Process\ProcessProfile;
|
use App\Process\ProcessProfile;
|
||||||
use App\Process\ProcessSettings;
|
use App\Process\ProcessSettings;
|
||||||
|
use App\Support\Money;
|
||||||
use BackedEnum;
|
use BackedEnum;
|
||||||
use Filament\Pages\Page;
|
use Filament\Pages\Page;
|
||||||
use Filament\Support\Icons\Heroicon;
|
use Filament\Support\Icons\Heroicon;
|
||||||
@@ -63,8 +65,11 @@ public function matrix(): array
|
|||||||
$settings = app(ProcessSettings::class);
|
$settings = app(ProcessSettings::class);
|
||||||
|
|
||||||
return Property::query()->orderBy('name')->get()->map(function (Property $property) use ($settings): array {
|
return Property::query()->orderBy('name')->get()->map(function (Property $property) use ($settings): array {
|
||||||
$columns = [['label' => 'Direkte Anfrage (Webseite, Telefon)', 'profile' => $settings->resolve($property, null, IntakeKind::Inquiry)]];
|
$columns = [
|
||||||
foreach (Channel::query()->where('property_id', $property->id)->orderBy('name')->get() as $channel) {
|
['label' => 'Eigene Webseite – Anfrage', 'profile' => $settings->forWebsite($property)],
|
||||||
|
['label' => 'Direkte Anfrage (Telefon, E-Mail)', 'profile' => $settings->resolve($property, null, IntakeKind::Inquiry)],
|
||||||
|
];
|
||||||
|
foreach (Channel::query()->portals()->where('property_id', $property->id)->orderBy('name')->get() as $channel) {
|
||||||
$columns[] = ['label' => $channel->name.' – Anfrage', 'profile' => $settings->resolve($property, $channel, IntakeKind::Inquiry)];
|
$columns[] = ['label' => $channel->name.' – Anfrage', 'profile' => $settings->resolve($property, $channel, IntakeKind::Inquiry)];
|
||||||
$columns[] = ['label' => $channel->name.' – feste Buchung', 'profile' => $settings->resolve($property, $channel, IntakeKind::Booking)];
|
$columns[] = ['label' => $channel->name.' – feste Buchung', 'profile' => $settings->resolve($property, $channel, IntakeKind::Booking)];
|
||||||
}
|
}
|
||||||
@@ -102,6 +107,39 @@ public static function where(ProcessSetting $setting): string
|
|||||||
: 'System › So arbeite ich; Abweichung: Wohnung (Experte), Portal je Anfrage/feste Buchung'.($setting->channelIntakes() === [] ? ' (kein Portal)' : '');
|
: 'System › So arbeite ich; Abweichung: Wohnung (Experte), Portal je Anfrage/feste Buchung'.($setting->channelIntakes() === [] ? ' (kein Portal)' : '');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a request on this way is answered with (package 7): a binding offer that reserves, or an information.
|
||||||
|
*/
|
||||||
|
public static function answer(ProcessProfile $profile): string
|
||||||
|
{
|
||||||
|
return match ($profile->intake) {
|
||||||
|
IntakeKind::Inquiry => $profile->inquiryAnswer() === InquiryAnswer::Offer
|
||||||
|
? 'Angebot mit Annahmelink'.($profile->preReservation() ? ', Zeitraum schon bei der Anfrage reserviert' : ', Zeitraum erst mit dem Angebot reserviert')
|
||||||
|
: 'Unverbindliche Auskunft, „Buchung anfragen“, erneute Prüfung',
|
||||||
|
IntakeKind::Booking => 'keine – beim Portal bereits verbindlich',
|
||||||
|
IntakeKind::Internal => 'keine – eigene Belegung',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The stay settings of a property in one line (package 9).
|
||||||
|
*/
|
||||||
|
public static function stay(Property $property): string
|
||||||
|
{
|
||||||
|
$tasks = array_map(fn (array $task): string => $task['title'].' ('.match ($task['when']) {
|
||||||
|
'after_departure' => 'am Abreisetag',
|
||||||
|
'on_arrival' => 'am Anreisetag',
|
||||||
|
default => $task['days'].' Tag(e) vor Anreise',
|
||||||
|
}.($task['responsible'] ? ', '.$task['responsible'] : '').')', $property->stayTaskDefinitions());
|
||||||
|
|
||||||
|
return implode(' · ', [
|
||||||
|
'Anreisezeit erfragen: '.($property->asks_arrival_time ? 'ja' : 'nein'),
|
||||||
|
'Aufgaben je Aufenthalt: '.($tasks === [] ? 'keine eingestellt' : implode(', ', $tasks)),
|
||||||
|
'gebuchte Leistungen werden zu Aufgaben',
|
||||||
|
'Kurabgabe (A6): '.($property->tourist_tax_rate ? Money::format((int) $property->tourist_tax_rate).' je Person und Nacht' : 'kein Satz – keine Berechnung'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Recent cases to check.
|
* Recent cases to check.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -3,15 +3,19 @@
|
|||||||
namespace App\Filament\Pages;
|
namespace App\Filament\Pages;
|
||||||
|
|
||||||
use App\Actions\SendDigests;
|
use App\Actions\SendDigests;
|
||||||
|
use App\Channels\ChannelSyncException;
|
||||||
|
use App\Channels\Mail\MailboxReader;
|
||||||
use App\Enums\DigestSection;
|
use App\Enums\DigestSection;
|
||||||
use App\Enums\TenantServiceKey;
|
use App\Enums\TenantServiceKey;
|
||||||
use App\Enums\UserRole;
|
use App\Enums\UserRole;
|
||||||
use App\Filament\Concerns\FollowsAdminMode;
|
use App\Filament\Concerns\FollowsAdminMode;
|
||||||
|
use App\Models\Mailbox;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Support\Settings;
|
use App\Support\Settings;
|
||||||
use App\Tenancy\TenantConfig;
|
use App\Tenancy\TenantConfig;
|
||||||
use App\Tenancy\TenantFeatures;
|
use App\Tenancy\TenantFeatures;
|
||||||
use BackedEnum;
|
use BackedEnum;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
use Filament\Actions\Action;
|
use Filament\Actions\Action;
|
||||||
use Filament\Forms\Components\CheckboxList;
|
use Filament\Forms\Components\CheckboxList;
|
||||||
use Filament\Forms\Components\Radio;
|
use Filament\Forms\Components\Radio;
|
||||||
@@ -29,6 +33,7 @@
|
|||||||
use Filament\Schemas\Components\Utilities\Get;
|
use Filament\Schemas\Components\Utilities\Get;
|
||||||
use Filament\Schemas\Schema;
|
use Filament\Schemas\Schema;
|
||||||
use Filament\Support\Icons\Heroicon;
|
use Filament\Support\Icons\Heroicon;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
use UnitEnum;
|
use UnitEnum;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -102,12 +107,14 @@ public function mount(): void
|
|||||||
'bank_iban' => $tenant->bank_iban,
|
'bank_iban' => $tenant->bank_iban,
|
||||||
'bank_bic' => $tenant->bank_bic,
|
'bank_bic' => $tenant->bank_bic,
|
||||||
'tax_note' => $tenant->tax_note,
|
'tax_note' => $tenant->tax_note,
|
||||||
'mailbox_host' => $tenant->mailbox_host,
|
'mailbox_host' => $tenant->activeMailbox()?->host ?? $tenant->mailbox_host,
|
||||||
'mailbox_port' => $tenant->mailbox_port,
|
'mailbox_port' => $tenant->activeMailbox()?->port ?? $tenant->mailbox_port,
|
||||||
'mailbox_username' => $tenant->mailbox_username,
|
'mailbox_username' => $tenant->activeMailbox()?->username ?? $tenant->mailbox_username,
|
||||||
'mailbox_password' => $tenant->mailbox_password,
|
'mailbox_password' => $tenant->activeMailbox()?->password ?? $tenant->mailbox_password,
|
||||||
'mailbox_encryption' => $tenant->mailbox_encryption,
|
'mailbox_encryption' => $tenant->activeMailbox()?->encryption ?? $tenant->mailbox_encryption,
|
||||||
'mailbox_folder' => $tenant->mailbox_folder,
|
'mailbox_folder' => $tenant->activeMailbox()?->folder ?? $tenant->mailbox_folder,
|
||||||
|
'mailbox_address' => $tenant->activeMailbox()?->address,
|
||||||
|
'mailbox_mode' => $tenant->activeMailbox()?->mode ?? Mailbox::PORTAL_ONLY,
|
||||||
'reminder_interval_days' => $tenant->reminder_interval_days,
|
'reminder_interval_days' => $tenant->reminder_interval_days,
|
||||||
'digest_daily' => $tenant->digest_daily,
|
'digest_daily' => $tenant->digest_daily,
|
||||||
'digest_weekly' => $tenant->digest_weekly,
|
'digest_weekly' => $tenant->digest_weekly,
|
||||||
@@ -247,8 +254,20 @@ public function form(Schema $schema): Schema
|
|||||||
Select::make('mailbox_encryption')
|
Select::make('mailbox_encryption')
|
||||||
->label('Verschlüsselung')
|
->label('Verschlüsselung')
|
||||||
->options(['ssl' => 'SSL', 'tls' => 'TLS', 'starttls' => 'STARTTLS'])
|
->options(['ssl' => 'SSL', 'tls' => 'TLS', 'starttls' => 'STARTTLS'])
|
||||||
->placeholder('SSL'),
|
->placeholder('Standard (SSL)'),
|
||||||
TextInput::make('mailbox_folder')->label('Ordner')->placeholder('INBOX')->maxLength(190),
|
TextInput::make('mailbox_folder')->label('Ordner')->placeholder('INBOX')->maxLength(190)
|
||||||
|
->helperText('Leer lassen für den Posteingang (auf dem Server „INBOX“, auch „Posteingang“ wird erkannt).'),
|
||||||
|
Select::make('mailbox_mode')->label('Was wird gelesen?')
|
||||||
|
->options([Mailbox::PORTAL_ONLY => 'Nur Buchungsmails der Portale (wie bisher)', Mailbox::FULL => 'Alle Nachrichten (eigenes Postfach für die Gästekommunikation)'])
|
||||||
|
->required()
|
||||||
|
->helperText('„Alle Nachrichten“ nur für ein Postfach, das ausschließlich für Anfragen und Gästeantworten dient: Antworten und Gast-Mails werden dann den Vorgängen zugeordnet oder im Posteingang zur Klärung gezeigt.'),
|
||||||
|
TextInput::make('mailbox_address')->label('Adresse dieses Postfachs (für Antworten der Gäste)')->email()->maxLength(190)
|
||||||
|
->helperText('Rückfragen nennen diese Adresse als Antwortadresse, damit die Antwort hier ankommt.'),
|
||||||
|
Text::make(fn (): string => $this->mailboxState())->columnSpanFull(),
|
||||||
|
Actions::make([
|
||||||
|
Action::make('checkMailbox')->label('Postfach prüfen')->icon(Heroicon::OutlinedSignal)->color('gray')
|
||||||
|
->action(fn () => $this->checkMailbox()),
|
||||||
|
])->columnSpanFull(),
|
||||||
]),
|
]),
|
||||||
Section::make('Fristen und Grenzen')
|
Section::make('Fristen und Grenzen')
|
||||||
->description('Leer bedeutet: die Vorgabe des Systems gilt. Löschfristen und Bot-Schutz lassen sich verschärfen, aber nicht über die Vorgabe hinaus lockern.')
|
->description('Leer bedeutet: die Vorgabe des Systems gilt. Löschfristen und Bot-Schutz lassen sich verschärfen, aber nicht über die Vorgabe hinaus lockern.')
|
||||||
@@ -291,6 +310,47 @@ protected function getHeaderActions(): array
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connects to the saved mailbox and counts the messages of the last days; nothing is read or marked.
|
||||||
|
*/
|
||||||
|
public function checkMailbox(): void
|
||||||
|
{
|
||||||
|
$connection = $this->tenant()->mailbox();
|
||||||
|
if ($connection === null) {
|
||||||
|
Notification::make()->title('Kein Postfach gespeichert')->body('Bitte Server und Benutzer eintragen und speichern.')->warning()->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$count = app(MailboxReader::class)->probe($connection);
|
||||||
|
} catch (ChannelSyncException $exception) {
|
||||||
|
Notification::make()->title('Postfach nicht erreichbar')->body($exception->getMessage())->danger()->persistent()->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Notification::make()->title('Verbindung in Ordnung')->body($count.' Nachricht(en) der letzten '.config('fewo.mailbox.lookback_days', 3).' Tage im Ordner „'.$connection['folder'].'“.')->success()->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When the mailbox was last read and whether the last attempt failed.
|
||||||
|
*/
|
||||||
|
private function mailboxState(): string
|
||||||
|
{
|
||||||
|
$mailbox = $this->tenant()->activeMailbox();
|
||||||
|
if ($mailbox === null || blank($mailbox->host)) {
|
||||||
|
return 'Kein Postfach eingerichtet.';
|
||||||
|
}
|
||||||
|
|
||||||
|
$error = Cache::get(MailboxReader::key(MailboxReader::LAST_ERROR_KEY));
|
||||||
|
$success = Cache::get(MailboxReader::key(MailboxReader::LAST_SUCCESS_KEY));
|
||||||
|
|
||||||
|
return 'Abruf jede Minute. Zuletzt erfolgreich gelesen: '.($success ? CarbonImmutable::parse($success)->format('d.m.Y, H:i').' Uhr' : 'noch nie')
|
||||||
|
.($error ? ' · Letzter Fehler: '.mb_substr((string) $error, 0, 200) : '')
|
||||||
|
.($mailbox->readsEverything() ? ' · Eingegangene Nachrichten stehen unter Verwaltung › Posteingang.' : ' · Gelesen werden nur Buchungsmails der Portale.');
|
||||||
|
}
|
||||||
|
|
||||||
public function save(): void
|
public function save(): void
|
||||||
{
|
{
|
||||||
$data = $this->form->getState();
|
$data = $this->form->getState();
|
||||||
@@ -329,6 +389,22 @@ public function save(): void
|
|||||||
...array_map(fn (mixed $value): ?int => filled($value) ? (int) $value : null, $this->periodInput($data)),
|
...array_map(fn (mixed $value): ?int => filled($value) ? (int) $value : null, $this->periodInput($data)),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
// v0.11 (CH-05): the active mailbox record leads; it is kept in step with the fields above.
|
||||||
|
$mailbox = $tenant->activeMailbox() ?? new Mailbox(['is_active' => true]);
|
||||||
|
$mailbox->forceFill(['tenant_id' => $tenant->id])->fill([
|
||||||
|
'host' => $data['mailbox_host'] ?? null,
|
||||||
|
'port' => filled($data['mailbox_port'] ?? null) ? (int) $data['mailbox_port'] : null,
|
||||||
|
'username' => $data['mailbox_username'] ?? null,
|
||||||
|
'password' => $data['mailbox_password'] ?? null,
|
||||||
|
'encryption' => $data['mailbox_encryption'] ?? null,
|
||||||
|
'folder' => $data['mailbox_folder'] ?? null,
|
||||||
|
'address' => $data['mailbox_address'] ?? null,
|
||||||
|
'mode' => $data['mailbox_mode'] ?? Mailbox::PORTAL_ONLY,
|
||||||
|
]);
|
||||||
|
if ($mailbox->exists || filled($mailbox->host)) {
|
||||||
|
$mailbox->save();
|
||||||
|
}
|
||||||
|
|
||||||
app(TenantConfig::class)->refresh();
|
app(TenantConfig::class)->refresh();
|
||||||
|
|
||||||
if ($data['mode'] === Settings::MODE_LIVE && ! $wasLive) {
|
if ($data['mode'] === Settings::MODE_LIVE && ! $wasLive) {
|
||||||
|
|||||||
@@ -147,7 +147,7 @@ public static function portalActions(): array
|
|||||||
->mapWithKeys(fn (BlockedPeriod $block): array => [$block->id => '#'.$block->id.' · '.$block->occupationKind()->getLabel().' · '.($block->reason ?? 'Kalenderbelegung').($block->leading_priority ? ' · bevorzugter Führungskandidat' : '')])->all();
|
->mapWithKeys(fn (BlockedPeriod $block): array => [$block->id => '#'.$block->id.' · '.$block->occupationKind()->getLabel().' · '.($block->reason ?? 'Kalenderbelegung').($block->leading_priority ? ' · bevorzugter Führungskandidat' : '')])->all();
|
||||||
}),
|
}),
|
||||||
Select::make('origin_channel_id')->label('Ursprünglicher Buchungskanal, sofern persönlich bekannt')
|
Select::make('origin_channel_id')->label('Ursprünglicher Buchungskanal, sofern persönlich bekannt')
|
||||||
->options(fn (BlockedPeriod $record): array => Channel::query()->where('property_id', $record->property_id)->pluck('name', 'id')->all())
|
->options(fn (BlockedPeriod $record): array => Channel::query()->portals()->where('property_id', $record->property_id)->pluck('name', 'id')->all())
|
||||||
->default(fn (BlockedPeriod $record): ?int => $record->origin_channel_id)->placeholder('Unbekannt / eigene Vermietung'),
|
->default(fn (BlockedPeriod $record): ?int => $record->origin_channel_id)->placeholder('Unbekannt / eigene Vermietung'),
|
||||||
])
|
])
|
||||||
->action(function (BlockedPeriod $record, array $data, ResolveChannelOccupation $resolve): void {
|
->action(function (BlockedPeriod $record, array $data, ResolveChannelOccupation $resolve): void {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
use App\Filament\Resources\Bookings\Pages\CreateBooking;
|
use App\Filament\Resources\Bookings\Pages\CreateBooking;
|
||||||
use App\Filament\Resources\Bookings\Pages\ListBookings;
|
use App\Filament\Resources\Bookings\Pages\ListBookings;
|
||||||
use App\Filament\Resources\Bookings\Pages\ViewBooking;
|
use App\Filament\Resources\Bookings\Pages\ViewBooking;
|
||||||
|
use App\Filament\Resources\Bookings\RelationManagers\InboundMessagesRelationManager;
|
||||||
use App\Filament\Resources\Bookings\RelationManagers\MessagesRelationManager;
|
use App\Filament\Resources\Bookings\RelationManagers\MessagesRelationManager;
|
||||||
use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager;
|
use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager;
|
||||||
use App\Filament\Resources\Bookings\RelationManagers\TasksRelationManager;
|
use App\Filament\Resources\Bookings\RelationManagers\TasksRelationManager;
|
||||||
@@ -76,6 +77,7 @@ public static function getRelations(): array
|
|||||||
PaymentsRelationManager::class,
|
PaymentsRelationManager::class,
|
||||||
TasksRelationManager::class,
|
TasksRelationManager::class,
|
||||||
MessagesRelationManager::class,
|
MessagesRelationManager::class,
|
||||||
|
InboundMessagesRelationManager::class,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,299 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\Bookings\Pages\Concerns;
|
||||||
|
|
||||||
|
use App\Actions\CloseStay;
|
||||||
|
use App\Actions\DecideBookingWish;
|
||||||
|
use App\Actions\PrepareStays;
|
||||||
|
use App\Actions\SendInformation;
|
||||||
|
use App\Actions\SendOffer;
|
||||||
|
use App\Availability\AvailabilityChecker;
|
||||||
|
use App\Enums\BookingStatus;
|
||||||
|
use App\Enums\BookingTaskKind;
|
||||||
|
use App\Enums\BookingTaskStatus;
|
||||||
|
use App\Enums\DocumentKind;
|
||||||
|
use App\Enums\InquiryAnswer;
|
||||||
|
use App\Enums\IntakeKind;
|
||||||
|
use App\Enums\Responsibility;
|
||||||
|
use App\Exceptions\ReservationException;
|
||||||
|
use App\Filament\Forms\DocumentCompositionFields;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\BookingTask;
|
||||||
|
use App\Pricing\CaseMoney;
|
||||||
|
use App\Pricing\StayRequest;
|
||||||
|
use App\Process\CaseClosure;
|
||||||
|
use App\Process\CaseLog;
|
||||||
|
use App\Support\Money;
|
||||||
|
use Filament\Actions\Action;
|
||||||
|
use Filament\Forms\Components\DatePicker;
|
||||||
|
use Filament\Forms\Components\DateTimePicker;
|
||||||
|
use Filament\Forms\Components\Hidden;
|
||||||
|
use Filament\Forms\Components\Radio;
|
||||||
|
use Filament\Forms\Components\Select;
|
||||||
|
use Filament\Forms\Components\Textarea;
|
||||||
|
use Filament\Forms\Components\TextInput;
|
||||||
|
use Filament\Notifications\Notification;
|
||||||
|
use Filament\Schemas\Components\Section;
|
||||||
|
use Filament\Schemas\Components\Text;
|
||||||
|
use Filament\Schemas\Components\Utilities\Get;
|
||||||
|
use Filament\Support\Icons\Heroicon;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Case page actions of packages 7 and 9: the information "unter Vorbehalt" and the decision on a booking wish; arrival
|
||||||
|
* details, tasks of the stay (done, handed over, newly noted), closing the stay and settling the case commercially.
|
||||||
|
*
|
||||||
|
* @property Booking $record
|
||||||
|
*/
|
||||||
|
trait HandlesWishAndStay
|
||||||
|
{
|
||||||
|
private function sendInformationAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('sendInformation')
|
||||||
|
->label(fn (): string => $this->record->information_version > 0 ? 'Auskunft ändern & neu senden' : 'Unverbindliche Auskunft prüfen und senden')
|
||||||
|
->icon(Heroicon::OutlinedPaperAirplane)
|
||||||
|
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking
|
||||||
|
&& $this->record->process()->inquiryAnswer() === InquiryAnswer::Information && $this->record->offer_version === 0 && ! $this->record->isHoldActive())
|
||||||
|
->modalHeading('Unverbindliche Auskunft an den Gast')
|
||||||
|
->modalDescription('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht. Der Gast erhält Preis und Verfügbarkeit zum heutigen Stand und kann daraus die Buchung anfragen; dann wird erneut geprüft. Verbindlich wird erst Ihre (oder die automatische) Bestätigung.')
|
||||||
|
->modalSubmitActionLabel('Senden')
|
||||||
|
->modalWidth('4xl')
|
||||||
|
->fillForm(fn (): array => [
|
||||||
|
'expected_version' => $this->record->information_version,
|
||||||
|
'arrival' => $this->record->arrival->toDateString(),
|
||||||
|
'departure' => $this->record->departure->toDateString(),
|
||||||
|
'guests' => $this->record->guests,
|
||||||
|
'promo_code' => $this->record->promo_code,
|
||||||
|
'price_adjustment' => $this->record->price_adjustment !== null ? number_format($this->record->price_adjustment / 100, 2, '.', '') : null,
|
||||||
|
'price_adjustment_label' => $this->record->price_adjustment_label,
|
||||||
|
'valid_until' => now()->addHours($this->record->process()->holdHours())->format('Y-m-d H:i'),
|
||||||
|
'offer_message' => $this->record->offer_message,
|
||||||
|
])
|
||||||
|
->schema([
|
||||||
|
Hidden::make('expected_version'),
|
||||||
|
...DocumentCompositionFields::make($this->record, DocumentKind::Information, fn (Get $get): array => $this->offerChanges(self::formState($get, ['expected_version', 'arrival', 'departure', 'guests', 'promo_code', 'price_adjustment', 'price_adjustment_label', 'valid_until', 'offer_message']))),
|
||||||
|
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3)->live(onBlur: true),
|
||||||
|
Section::make('Anpassen')->description('Zeitraum, Preis und wie lange der Gast die Buchung anfragen kann.')->collapsed()->schema([
|
||||||
|
Section::make('Termin')->columns(3)->schema([
|
||||||
|
DatePicker::make('arrival')->label('Anreise')->required()->live(onBlur: true),
|
||||||
|
DatePicker::make('departure')->label('Abreise')->after('arrival')->required()->live(onBlur: true),
|
||||||
|
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->maxValue(fn (): int => $this->record->property->max_guests)->required()->live(onBlur: true),
|
||||||
|
]),
|
||||||
|
Section::make('Preis')->columns(3)->schema([
|
||||||
|
TextInput::make('promo_code')->label('Rabattcode')->maxLength(50)->live(onBlur: true),
|
||||||
|
TextInput::make('price_adjustment')->label('Preisanpassung')->helperText('Minus = Nachlass, z. B. -50')->numeric()->step(0.01)->suffix('€')->live(onBlur: true),
|
||||||
|
TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80)->live(onBlur: true),
|
||||||
|
]),
|
||||||
|
DateTimePicker::make('valid_until')->label('Buchung anfragen bis')->helperText('Der Zeitraum bleibt bis dahin trotzdem frei buchbar für andere.')->seconds(false)->after('now')->required()->live(onBlur: true),
|
||||||
|
]),
|
||||||
|
])
|
||||||
|
->action(fn (array $data, SendInformation $send) => $this->runWorkflow(fn () => $send->handle($this->record, $this->offerChanges($data)), 'Auskunft gesendet'));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function decideWishAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('decideWish')
|
||||||
|
->label('Buchungswunsch bestätigen oder absagen …')
|
||||||
|
->icon(Heroicon::OutlinedCheckCircle)
|
||||||
|
->visible(fn (): bool => $this->record->status === BookingStatus::Reserved && $this->record->wish_at !== null)
|
||||||
|
->modalHeading('Buchungswunsch des Gastes')
|
||||||
|
->modalDescription(fn (): string => 'Angefragt am '.$this->record->wish_at?->format('d.m.Y, H:i').' Uhr. Bei „Bestätigen“ wird die Verfügbarkeit noch einmal geprüft; der Gast erhält die Buchungsbestätigung mit dem Mietvertrag.')
|
||||||
|
->modalSubmitActionLabel('Ausführen')
|
||||||
|
->schema(fn (): array => [
|
||||||
|
Text::make($this->wishCheckText()),
|
||||||
|
Radio::make('decision')->label('Entscheidung')->required()->default('confirm')->live()->options(array_filter([
|
||||||
|
'confirm' => 'Bestätigen zum Preis der Auskunft ('.Money::format((int) $this->record->total).')',
|
||||||
|
'confirm_today' => $this->todaysTotal() !== null && $this->todaysTotal() < (int) $this->record->total ? 'Bestätigen zum heutigen, niedrigeren Preis ('.Money::format((int) $this->todaysTotal()).')' : null,
|
||||||
|
'decline' => 'Absagen – der Gast erhält eine freundliche Absage',
|
||||||
|
])),
|
||||||
|
Textarea::make('reason')->label('Grund (nur für den Verlauf)')->rows(2)->visible(fn (Get $get): bool => $get('decision') === 'decline'),
|
||||||
|
])
|
||||||
|
->action(function (array $data, DecideBookingWish $decide): void {
|
||||||
|
$this->runWorkflow(fn () => match ($data['decision']) {
|
||||||
|
'decline' => $decide->decline($this->record, $data['reason'] ?? null),
|
||||||
|
default => $decide->confirm($this->record, $data['decision'] === 'confirm_today'),
|
||||||
|
}, $data['decision'] === 'decline' ? 'Abgesagt' : 'Buchung bestätigt');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function arrivalDetailsAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('arrivalDetails')
|
||||||
|
->label('Anreisedaten eintragen')
|
||||||
|
->icon(Heroicon::OutlinedClock)
|
||||||
|
->visible(fn (): bool => $this->record->isBinding() && ! $this->record->isInternal() && $this->record->departure->isFuture())
|
||||||
|
->modalHeading('Anreisedaten')
|
||||||
|
->modalDescription('Aus Portalnachricht, E-Mail oder Telefonat. Was fehlt, steht in der Aufgabe; nur Bekanntes eintragen.')
|
||||||
|
->fillForm(fn (): array => ['arrival_time' => $this->record->arrival_time, 'email' => $this->record->guest?->email, 'phone' => $this->record->guest?->phone])
|
||||||
|
->schema([
|
||||||
|
TextInput::make('arrival_time')->label('Anreisezeit')->placeholder('z. B. gegen 16 Uhr')->maxLength(40),
|
||||||
|
TextInput::make('phone')->label('Telefon des Gastes')->tel()->maxLength(50)->visible(fn (): bool => $this->record->guest !== null),
|
||||||
|
TextInput::make('email')->label('E-Mail des Gastes')->email()->maxLength(255)->visible(fn (): bool => $this->record->guest !== null),
|
||||||
|
])
|
||||||
|
->action(function (array $data): void {
|
||||||
|
$this->record->update(['arrival_time' => filled($data['arrival_time'] ?? null) ? trim((string) $data['arrival_time']) : null]);
|
||||||
|
if ($this->record->guest !== null) {
|
||||||
|
$this->record->guest->update(array_filter(['phone' => $data['phone'] ?? null, 'email' => isset($data['email']) ? mb_strtolower(trim((string) $data['email'])) : null], fn ($value): bool => filled($value)));
|
||||||
|
}
|
||||||
|
app(PrepareStays::class)->handle();
|
||||||
|
$this->record->refresh();
|
||||||
|
Notification::make()->title('Gespeichert')->success()->send();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function completeTaskAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('completeTask')
|
||||||
|
->label('Aufgabe erledigen …')
|
||||||
|
->icon(Heroicon::OutlinedCheck)
|
||||||
|
->visible(fn (): bool => $this->openTasks() !== [])
|
||||||
|
->modalHeading('Aufgabe erledigen')
|
||||||
|
->modalDescription('Erledigt oder an jemanden übergeben (z. B. Reinigung, Portal, Steuerberater). Die Notiz steht im Verlauf.')
|
||||||
|
->fillForm(fn (): array => ['task' => array_key_first($this->openTasks()), 'outcome' => 'done'])
|
||||||
|
->schema([
|
||||||
|
Select::make('task')->label('Aufgabe')->options(fn (): array => $this->openTasks())->required(),
|
||||||
|
Radio::make('outcome')->label('Ergebnis')->required()->options([
|
||||||
|
'done' => 'Erledigt',
|
||||||
|
'handed_over' => 'Übergeben – jemand anderes kümmert sich',
|
||||||
|
'dismissed' => 'Entfällt',
|
||||||
|
])->live(),
|
||||||
|
TextInput::make('handed_to')->label('Übergeben an')->maxLength(120)->required(fn (Get $get): bool => $get('outcome') === 'handed_over')->visible(fn (Get $get): bool => $get('outcome') === 'handed_over'),
|
||||||
|
Textarea::make('note')->label('Notiz')->rows(2)->maxLength(1000),
|
||||||
|
])
|
||||||
|
->action(function (array $data): void {
|
||||||
|
$task = BookingTask::query()->where('booking_id', $this->record->id)->whereKey($data['task'])->where('status', BookingTaskStatus::Open)->first();
|
||||||
|
if ($task === null) {
|
||||||
|
Notification::make()->title('Diese Aufgabe ist schon erledigt.')->warning()->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$note = trim(implode(' · ', array_filter([$data['outcome'] === 'handed_over' ? 'Übergeben an '.$data['handed_to'] : null, $data['note'] ?? null])));
|
||||||
|
if ($data['outcome'] === 'dismissed') {
|
||||||
|
$task->update(['status' => BookingTaskStatus::Dismissed, 'note' => $note !== '' ? $note : $task->note, 'completed_by' => CaseLog::actor(), 'completed_at' => now()]);
|
||||||
|
} else {
|
||||||
|
if ($data['outcome'] === 'handed_over') {
|
||||||
|
$task->responsible = (string) $data['handed_to'];
|
||||||
|
}
|
||||||
|
$task->complete(CaseLog::actor(), $note !== '' ? $note : null);
|
||||||
|
}
|
||||||
|
$this->record->refresh();
|
||||||
|
Notification::make()->title('Aufgabe vermerkt')->success()->send();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function addTaskAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('addTask')
|
||||||
|
->label('Abweichung oder Aufgabe festhalten …')
|
||||||
|
->icon(Heroicon::OutlinedPencilSquare)
|
||||||
|
->visible(fn (): bool => in_array($this->record->status, [...BookingStatus::occupying(), BookingStatus::Cancelled], true))
|
||||||
|
->modalHeading('Abweichung oder Aufgabe festhalten')
|
||||||
|
->modalDescription('Zum Aufenthalt (z. B. späte Anreise, defekte Kaffeemaschine, Schaden) – als Aufgabe am Vorgang, keine eigene Verwaltung.')
|
||||||
|
->schema([
|
||||||
|
Radio::make('kind')->label('Art')->required()->default(BookingTaskKind::Issue->value)->options([
|
||||||
|
BookingTaskKind::Issue->value => 'Abweichung oder Problem beim Aufenthalt – muss vor dem Abschluss des Aufenthalts geklärt sein',
|
||||||
|
BookingTaskKind::Service->value => 'Leistung vorbereiten (z. B. Kinderbett, zusätzliche Reinigung)',
|
||||||
|
BookingTaskKind::FollowUp->value => 'Folgeaufgabe nach dem Aufenthalt (z. B. Schaden abrechnen, Reparatur) – hält den Abschluss nicht auf',
|
||||||
|
]),
|
||||||
|
TextInput::make('title')->label('Was?')->required()->maxLength(200),
|
||||||
|
TextInput::make('responsible')->label('Wer kümmert sich? (optional)')->placeholder('z. B. Reinigung Müller')->maxLength(120),
|
||||||
|
DatePicker::make('due_on')->label('Bis wann? (optional)'),
|
||||||
|
Textarea::make('note')->label('Notiz')->rows(2)->maxLength(1000),
|
||||||
|
])
|
||||||
|
->action(function (array $data): void {
|
||||||
|
BookingTask::openOnce($this->record, BookingTaskKind::from($data['kind']), 'manual:'.now()->format('YmdHisv'), [
|
||||||
|
'title' => trim((string) $data['title']),
|
||||||
|
'responsible' => filled($data['responsible'] ?? null) ? trim((string) $data['responsible']) : null,
|
||||||
|
'due_on' => $data['due_on'] ?? null,
|
||||||
|
'note' => $data['note'] ?? null,
|
||||||
|
]);
|
||||||
|
$this->record->refresh();
|
||||||
|
Notification::make()->title('Festgehalten')->success()->send();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function closeStayAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('closeStay')
|
||||||
|
->label(fn (): string => $this->record->isInternal() ? 'Abschließen …' : 'Aufenthalt abschließen …')
|
||||||
|
->icon(Heroicon::OutlinedFlag)
|
||||||
|
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid], true) && ! $this->record->departure->isFuture())
|
||||||
|
->modalHeading('Aufenthalt abschließen')
|
||||||
|
->modalDescription(fn (): string => ($blockers = CaseClosure::stayBlockers($this->record))->isEmpty()
|
||||||
|
? 'Für den Aufenthalt ist nichts mehr offen. Offene Zahlungen oder Auszahlungen bleiben als kaufmännische Punkte am Vorgang.'
|
||||||
|
: 'Noch offen für den Aufenthalt: '.$blockers->map(fn (BookingTask $task): string => $task->label())->implode(', ').'. Mit dem Abschluss werden sie als erledigt bzw. übergeben vermerkt.')
|
||||||
|
->schema([Textarea::make('note')->label('Notiz (z. B. „Reinigung erledigt, Schlüssel zurück“)')->rows(2)->maxLength(500)])
|
||||||
|
->action(fn (array $data, CloseStay $close) => $this->runWorkflow(fn () => $close->byHand($this->record, CaseLog::actor(), $data['note'] ?? null), 'Aufenthalt abgeschlossen'));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function settleAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('settle')
|
||||||
|
->label('Kaufmännisch abschließen …')
|
||||||
|
->icon(Heroicon::OutlinedBanknotes)
|
||||||
|
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Completed, BookingStatus::Cancelled], true) && $this->record->settled_at === null)
|
||||||
|
->modalHeading('Kaufmännisch abschließen')
|
||||||
|
->modalDescription(fn (): string => 'Noch offen: '.implode(' ', CaseClosure::commercialPoints($this->record)).' Abschließen nur, wenn das geklärt ist (z. B. kleine Differenz akzeptiert, Forderung ausgebucht).')
|
||||||
|
->schema([
|
||||||
|
// Decision O5: with portal collection an open payout needs its financial clarification, not only a reason.
|
||||||
|
Select::make('clarification')->label('Wie ist die Auszahlung geklärt?')
|
||||||
|
->options(CaseClosure::PAYOUT_CLARIFICATIONS)
|
||||||
|
->visible(fn (): bool => $this->payoutOpen())
|
||||||
|
->required(fn (): bool => $this->payoutOpen())
|
||||||
|
->helperText('Eine Meldung des Portals über die Auszahlung ist kein Nachweis des Geldeingangs. „Als offene Forderung weiterführen“ legt eine Aufgabe an; der Vorgang bleibt kaufmännisch offen.'),
|
||||||
|
Textarea::make('note')->label('Begründung')->required()->rows(2)->maxLength(500),
|
||||||
|
])
|
||||||
|
->action(function (array $data): void {
|
||||||
|
try {
|
||||||
|
CaseClosure::settle($this->record, trim((string) $data['note']), CaseLog::actor(), $data['clarification'] ?? null);
|
||||||
|
} catch (ReservationException $exception) {
|
||||||
|
Notification::make()->title('Nicht abgeschlossen')->body($exception->getMessage())->danger()->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$this->record->refresh();
|
||||||
|
Notification::make()->title($this->record->settled_at !== null ? 'Kaufmännisch abgeschlossen' : 'Als offene Forderung weitergeführt')->success()->send();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the portal's payout is open or deviating (decision O5).
|
||||||
|
*/
|
||||||
|
private function payoutOpen(): bool
|
||||||
|
{
|
||||||
|
return CaseMoney::of($this->record)->collector() === Responsibility::Portal
|
||||||
|
&& collect(CaseClosure::commercialPoints($this->record))->contains(fn (string $point): bool => str_contains($point, 'Auszahlung'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open tasks the landlord can settle on the page (not the ones with an action of their own).
|
||||||
|
*
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
private function openTasks(): array
|
||||||
|
{
|
||||||
|
return BookingTask::query()->where('booking_id', $this->record->id)->where('status', BookingTaskStatus::Open)
|
||||||
|
->whereNotIn('kind', [BookingTaskKind::BookingWish, BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported, BookingTaskKind::DepositReminder, BookingTaskKind::BalanceRequest, BookingTaskKind::BalanceReminder])
|
||||||
|
->orderByRaw('due_on is null')->orderBy('due_on')->orderBy('id')->get()
|
||||||
|
->mapWithKeys(fn (BookingTask $task): array => [$task->id => $task->label().($task->due_on ? ' (fällig '.$task->due_on->format('d.m.Y').')' : '')])->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function wishCheckText(): string
|
||||||
|
{
|
||||||
|
$wish = (array) ($this->record->wish ?? []);
|
||||||
|
$findings = (array) ($wish['findings'] ?? []);
|
||||||
|
$available = app(AvailabilityChecker::class)->isAvailable($this->record->property, $this->record->arrival, $this->record->departure, ignore: $this->record);
|
||||||
|
|
||||||
|
return ($available ? 'Der Zeitraum ist im Moment frei. ' : 'Achtung: Der Zeitraum ist inzwischen belegt – bitte absagen. ')
|
||||||
|
.($findings === [] ? 'Bei der Prüfung des Wunsches war alles in Ordnung.' : 'Bei der Prüfung des Wunsches fiel auf: '.implode(' ', $findings));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function todaysTotal(): ?int
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return app(SendOffer::class)->quoteFor($this->record, new StayRequest($this->record->arrival, $this->record->departure, $this->record->guests, $this->record->extras ?? [], $this->record->promo_code), (int) $this->record->price_adjustment, (string) ($this->record->price_adjustment_label ?: 'Zuschlag'))->total();
|
||||||
|
} catch (Throwable) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -47,7 +47,7 @@ protected function handleRecordCreation(array $data): Model
|
|||||||
$channel = filled($data['channel_id'] ?? null) ? Channel::query()->findOrFail($data['channel_id']) : null;
|
$channel = filled($data['channel_id'] ?? null) ? Channel::query()->findOrFail($data['channel_id']) : null;
|
||||||
$arrival = CarbonImmutable::parse($data['arrival']);
|
$arrival = CarbonImmutable::parse($data['arrival']);
|
||||||
$departure = CarbonImmutable::parse($data['departure']);
|
$departure = CarbonImmutable::parse($data['departure']);
|
||||||
$guest = Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']);
|
$guest = Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']);
|
||||||
|
|
||||||
if ($data['kind'] === BookingForm::EXTERNAL) {
|
if ($data['kind'] === BookingForm::EXTERNAL) {
|
||||||
return app(TakeOverExternalBooking::class)->handle($property, $channel, $arrival, $departure, [
|
return app(TakeOverExternalBooking::class)->handle($property, $channel, $arrival, $departure, [
|
||||||
|
|||||||
@@ -9,19 +9,24 @@
|
|||||||
use App\Actions\EndInternalCase;
|
use App\Actions\EndInternalCase;
|
||||||
use App\Actions\ProvideGuestContact;
|
use App\Actions\ProvideGuestContact;
|
||||||
use App\Actions\RecordPortalAmounts;
|
use App\Actions\RecordPortalAmounts;
|
||||||
|
use App\Actions\RequestCaseData;
|
||||||
use App\Actions\SendBookingDocuments;
|
use App\Actions\SendBookingDocuments;
|
||||||
|
use App\Actions\SendBookingNotice;
|
||||||
use App\Actions\SendOffer;
|
use App\Actions\SendOffer;
|
||||||
use App\Actions\SetBookingStatus;
|
use App\Actions\SetBookingStatus;
|
||||||
use App\Documents\OfferTerms;
|
use App\Documents\OfferTerms;
|
||||||
use App\Documents\RentalContract;
|
use App\Documents\RentalContract;
|
||||||
|
use App\Enums\ActivityState;
|
||||||
use App\Enums\AdminMode;
|
use App\Enums\AdminMode;
|
||||||
use App\Enums\AmountKind;
|
use App\Enums\AmountKind;
|
||||||
|
use App\Enums\BookingNoticeMode;
|
||||||
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\ChangeBasis;
|
use App\Enums\ChangeBasis;
|
||||||
use App\Enums\ChangeStatus;
|
use App\Enums\ChangeStatus;
|
||||||
use App\Enums\DocumentKind;
|
use App\Enums\DocumentKind;
|
||||||
|
use App\Enums\InquiryAnswer;
|
||||||
use App\Enums\IntakeKind;
|
use App\Enums\IntakeKind;
|
||||||
use App\Enums\InternalKind;
|
use App\Enums\InternalKind;
|
||||||
use App\Enums\ProcessingMode;
|
use App\Enums\ProcessingMode;
|
||||||
@@ -31,18 +36,26 @@
|
|||||||
use App\Filament\Forms\Components\EuroInput;
|
use App\Filament\Forms\Components\EuroInput;
|
||||||
use App\Filament\Forms\DocumentCompositionFields;
|
use App\Filament\Forms\DocumentCompositionFields;
|
||||||
use App\Filament\Resources\Bookings\BookingResource;
|
use App\Filament\Resources\Bookings\BookingResource;
|
||||||
|
use App\Filament\Resources\Bookings\Pages\Concerns\HandlesWishAndStay;
|
||||||
use App\Models\Booking;
|
use App\Models\Booking;
|
||||||
use App\Models\BookingChange;
|
use App\Models\BookingChange;
|
||||||
use App\Models\BookingTask;
|
use App\Models\BookingTask;
|
||||||
use App\Models\ContractAnnex;
|
use App\Models\ContractAnnex;
|
||||||
use App\Models\ContractTemplate;
|
use App\Models\ContractTemplate;
|
||||||
|
use App\Models\DataRequest;
|
||||||
use App\Models\Extra;
|
use App\Models\Extra;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Pricing\PrivateStayPrice;
|
use App\Pricing\PrivateStayPrice;
|
||||||
use App\Pricing\QuoteException;
|
use App\Pricing\QuoteException;
|
||||||
|
use App\Process\Activity;
|
||||||
|
use App\Process\ActivityDetails;
|
||||||
use App\Process\CaseActivities;
|
use App\Process\CaseActivities;
|
||||||
use App\Process\CaseAutomation;
|
use App\Process\CaseAutomation;
|
||||||
use App\Process\CaseLog;
|
use App\Process\CaseLog;
|
||||||
|
use App\Process\CaseRequirements;
|
||||||
|
use App\Process\PortalConfirmation;
|
||||||
|
use App\Process\ProcessRunner;
|
||||||
|
use App\Support\Countries;
|
||||||
use App\Support\Money;
|
use App\Support\Money;
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Filament\Actions\Action;
|
use Filament\Actions\Action;
|
||||||
@@ -79,6 +92,8 @@
|
|||||||
*/
|
*/
|
||||||
class ViewBooking extends ViewRecord
|
class ViewBooking extends ViewRecord
|
||||||
{
|
{
|
||||||
|
use HandlesWishAndStay;
|
||||||
|
|
||||||
protected static string $resource = BookingResource::class;
|
protected static string $resource = BookingResource::class;
|
||||||
|
|
||||||
/** Actions for the expert view only. */
|
/** Actions for the expert view only. */
|
||||||
@@ -94,16 +109,45 @@ public function getSubheading(): string|Htmlable|null
|
|||||||
return CaseActivities::situation($this->record);
|
return CaseActivities::situation($this->record);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Filament builds the header actions before an action runs; rebuild them afterwards so the large button already
|
||||||
|
* shows the next step instead of the one just done.
|
||||||
|
*/
|
||||||
|
protected function afterActionCalled(Action $action): void
|
||||||
|
{
|
||||||
|
parent::afterActionCalled($action);
|
||||||
|
|
||||||
|
$fresh = $this->record->exists ? $this->record->fresh() : null;
|
||||||
|
if ($fresh === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->record = $fresh;
|
||||||
|
$this->cachedHeaderActions = [];
|
||||||
|
$this->cacheInteractsWithHeaderActions();
|
||||||
|
}
|
||||||
|
|
||||||
protected function getHeaderActions(): array
|
protected function getHeaderActions(): array
|
||||||
{
|
{
|
||||||
$actions = collect([
|
$actions = collect([
|
||||||
|
$this->sendInformationAction(),
|
||||||
|
$this->decideWishAction(),
|
||||||
$this->sendOfferAction(),
|
$this->sendOfferAction(),
|
||||||
$this->provideContactAction(),
|
$this->provideContactAction(),
|
||||||
|
$this->arrivalDetailsAction(),
|
||||||
|
$this->completeTaskAction(),
|
||||||
|
$this->addTaskAction(),
|
||||||
|
$this->closeStayAction(),
|
||||||
|
$this->settleAction(),
|
||||||
$this->requestContactAction(),
|
$this->requestContactAction(),
|
||||||
|
$this->approveDataRequestAction(),
|
||||||
|
$this->stopDataRequestAction(),
|
||||||
AssignGuestAction::make(),
|
AssignGuestAction::make(),
|
||||||
$this->confirmAction(),
|
$this->confirmAction(),
|
||||||
$this->sendDocumentsAction(),
|
$this->sendDocumentsAction(),
|
||||||
$this->resendConfirmationAction(),
|
$this->resendConfirmationAction(),
|
||||||
|
$this->confirmPortalAction(),
|
||||||
|
$this->sendBookingNoticeAction(),
|
||||||
$this->portalPriceAction(),
|
$this->portalPriceAction(),
|
||||||
$this->changeAction(),
|
$this->changeAction(),
|
||||||
$this->confirmPortalCancellationAction(),
|
$this->confirmPortalCancellationAction(),
|
||||||
@@ -119,7 +163,9 @@ protected function getHeaderActions(): array
|
|||||||
$this->setStatusAction(),
|
$this->setStatusAction(),
|
||||||
])->keyBy(fn (Action $action): string => $action->getName());
|
])->keyBy(fn (Action $action): string => $action->getName());
|
||||||
|
|
||||||
$next = CaseActivities::next($this->record)?->action;
|
// While the case waits for the guest's missing details, entering them oneself (call, other mail) is the step at hand.
|
||||||
|
$next = CaseActivities::next($this->record)?->action
|
||||||
|
?? collect(CaseActivities::for($this->record))->first(fn ($activity): bool => $activity->key === 'contact' && $activity->action !== null)?->action;
|
||||||
$primary = $next !== null && $actions->has($next) ? $actions->pull($next)->color('primary')->size('lg')->icon(Heroicon::OutlinedArrowRightCircle) : null;
|
$primary = $next !== null && $actions->has($next) ? $actions->pull($next)->color('primary')->size('lg')->icon(Heroicon::OutlinedArrowRightCircle) : null;
|
||||||
$expert = $actions->only(self::EXPERT)->values()->all();
|
$expert = $actions->only(self::EXPERT)->values()->all();
|
||||||
$more = $actions->except(self::EXPERT)->values()->all();
|
$more = $actions->except(self::EXPERT)->values()->all();
|
||||||
@@ -143,7 +189,11 @@ private function isExpert(): bool
|
|||||||
private function sendOfferAction(): Action
|
private function sendOfferAction(): Action
|
||||||
{
|
{
|
||||||
return Action::make('sendOffer')
|
return Action::make('sendOffer')
|
||||||
->label(fn (): string => $this->record->status === BookingStatus::OfferSent ? 'Angebot ändern & neu senden' : 'Angebot prüfen und senden')
|
->label(fn (): string => match (true) {
|
||||||
|
$this->record->status === BookingStatus::OfferSent => 'Angebot ändern & neu senden',
|
||||||
|
$this->record->process()->inquiryAnswer() === InquiryAnswer::Information => 'Stattdessen verbindliches Angebot mit Reservierung senden',
|
||||||
|
default => 'Angebot prüfen und senden',
|
||||||
|
})
|
||||||
->icon(Heroicon::OutlinedPaperAirplane)
|
->icon(Heroicon::OutlinedPaperAirplane)
|
||||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking)
|
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking)
|
||||||
->modalHeading('Angebot an den Gast')
|
->modalHeading('Angebot an den Gast')
|
||||||
@@ -255,14 +305,18 @@ private function templateFields(): array
|
|||||||
private function provideContactAction(): Action
|
private function provideContactAction(): Action
|
||||||
{
|
{
|
||||||
return Action::make('provideContact')
|
return Action::make('provideContact')
|
||||||
->label(fn (): string => $this->record->guest === null ? 'Gast eintragen' : 'Kontaktdaten eintragen')
|
->label(fn (): string => match (true) {
|
||||||
|
$this->record->guest === null => 'Gast eintragen',
|
||||||
|
RequestCaseData::needs($this->record) !== null => 'Fehlende Angaben selbst eintragen',
|
||||||
|
default => 'Gastdaten bearbeiten',
|
||||||
|
})
|
||||||
->icon(Heroicon::OutlinedUserPlus)
|
->icon(Heroicon::OutlinedUserPlus)
|
||||||
->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
|
->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
|
||||||
->modalHeading('Kontaktdaten des Gastes')
|
->modalHeading('Kontaktdaten des Gastes')
|
||||||
->modalDescription('Aus Portalnachricht, E-Mail oder Telefonat. Nur eintragen, was bekannt ist.')
|
->modalDescription(fn (): string => 'Aus Telefonat, E-Mail, Portalnachricht oder Gespräch. Nur eintragen, was bekannt ist; Ihre Eingabe gilt und wird mit Herkunft „von Ihnen eingetragen“ festgehalten. Eine laufende Rückfrage endet, sobald alles da ist.'.$this->openFactConflicts())
|
||||||
->modalWidth('3xl')
|
->modalWidth('3xl')
|
||||||
->fillForm(fn (): array => [
|
->fillForm(fn (): array => [
|
||||||
'guest' => $this->record->guest?->only(['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']) ?? [],
|
'guest' => $this->record->guest?->only(['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']) ?? [],
|
||||||
'process' => $this->record->processingMode() === ProcessingMode::Automatic ? ProvideGuestContact::AUTOMATIC : ProvideGuestContact::MANUAL,
|
'process' => $this->record->processingMode() === ProcessingMode::Automatic ? ProvideGuestContact::AUTOMATIC : ProvideGuestContact::MANUAL,
|
||||||
'guest_confirmed' => $this->record->guest_confirmed_at !== null,
|
'guest_confirmed' => $this->record->guest_confirmed_at !== null,
|
||||||
])
|
])
|
||||||
@@ -275,6 +329,7 @@ private function provideContactAction(): Action
|
|||||||
TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150),
|
TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150),
|
||||||
TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20),
|
TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20),
|
||||||
TextInput::make('guest.city')->label('Ort')->maxLength(100),
|
TextInput::make('guest.city')->label('Ort')->maxLength(100),
|
||||||
|
Select::make('guest.country')->label('Land')->options(Countries::options())->placeholder('nicht bekannt'),
|
||||||
]),
|
]),
|
||||||
Section::make('Wie geht es danach weiter?')->schema([
|
Section::make('Wie geht es danach weiter?')->schema([
|
||||||
Radio::make('process')->hiddenLabel()->options([
|
Radio::make('process')->hiddenLabel()->options([
|
||||||
@@ -299,6 +354,96 @@ private function provideContactAction(): Action
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Details from the guest's side that differ from the stored ones (v0.11 fact intake), for the contact dialog.
|
||||||
|
*/
|
||||||
|
private function openFactConflicts(): string
|
||||||
|
{
|
||||||
|
$notes = $this->record->tasks()->where('kind', BookingTaskKind::FactConflict)->where('status', BookingTaskStatus::Open)->pluck('note')->all();
|
||||||
|
|
||||||
|
return $notes === [] ? '' : ' Abweichende Angaben des Gastes – bitte den richtigen Wert eintragen: '.implode(' · ', $notes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What lies behind one step of the progress list (clicked in "Ablauf"): its history entries and – for the guest's
|
||||||
|
* details – each detail with source, time, evidence and certainty, with the way to correct it or to do the step.
|
||||||
|
*/
|
||||||
|
public function activityDetailsAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('activityDetails')
|
||||||
|
->modalHeading(fn (array $arguments): string => ActivityDetails::activity($this->record, (string) ($arguments['key'] ?? ''))?->label ?? 'Schritt')
|
||||||
|
->modalWidth('4xl')
|
||||||
|
->modalSubmitAction(false)
|
||||||
|
->modalCancelActionLabel('Schließen')
|
||||||
|
->modalContent(function (array $arguments): \Illuminate\Contracts\View\View {
|
||||||
|
$key = (string) ($arguments['key'] ?? '');
|
||||||
|
$activity = ActivityDetails::activity($this->record, $key);
|
||||||
|
|
||||||
|
return view('filament.activity-details', [
|
||||||
|
'activity' => $activity ?? new Activity($key, 'Schritt', ActivityState::NotApplicable),
|
||||||
|
'events' => ActivityDetails::events($this->record, $key),
|
||||||
|
'facts' => ActivityDetails::showsFacts($key) ? ActivityDetails::facts($this->record->loadMissing('guest')) : null,
|
||||||
|
]);
|
||||||
|
})
|
||||||
|
->extraModalFooterActions(fn (array $arguments): array => array_values(array_filter([
|
||||||
|
ActivityDetails::showsFacts((string) ($arguments['key'] ?? '')) && $this->record->internal_kind !== InternalKind::Block
|
||||||
|
? Action::make('correctFacts')->label('Angaben korrigieren')->color('primary')->action(fn () => $this->replaceMountedAction('provideContact'))
|
||||||
|
: null,
|
||||||
|
($step = ActivityDetails::activity($this->record, (string) ($arguments['key'] ?? ''))?->action) !== null && $step !== 'provideContact'
|
||||||
|
? Action::make('doStep')->label('Diesen Schritt ausführen')->action(fn () => $this->replaceMountedAction($step))
|
||||||
|
: null,
|
||||||
|
])));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* v0.11 data request: send the prepared question (or ask now although the case is set to asking by hand).
|
||||||
|
*/
|
||||||
|
private function approveDataRequestAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('approveDataRequest')
|
||||||
|
->label('Rückfrage an den Gast senden')
|
||||||
|
->icon(Heroicon::OutlinedPaperAirplane)
|
||||||
|
->visible(fn (): bool => in_array($this->record->openDataRequest()?->status, [DataRequest::DRAFT, DataRequest::MANUAL], true) && filled($this->record->guest?->email))
|
||||||
|
->modalHeading('Fehlende Angaben beim Gast anfragen')
|
||||||
|
->modalDescription(function (): string {
|
||||||
|
$request = $this->record->openDataRequest();
|
||||||
|
$state = $this->record->clarificationState();
|
||||||
|
|
||||||
|
return 'Der Gast erhält eine E-Mail mit einem persönlichen Link und wird gebeten um: '.implode(', ', CaseRequirements::labels((array) $request?->fields)).'. '
|
||||||
|
.match ($state['state']) {
|
||||||
|
'active' => 'Die Mail nennt die vorläufige Reservierung bis '.$state['until']->format('d.m.Y, H:i').' Uhr.',
|
||||||
|
'expired' => 'Die Mail sagt, dass die vorläufige Reservierung abgelaufen ist.',
|
||||||
|
default => $this->record->isBinding() ? 'Die Mail sagt, dass die Buchung verbindlich bleibt.' : 'Die Mail sagt, dass der Zeitraum noch nicht reserviert ist.',
|
||||||
|
}
|
||||||
|
.(RequestCaseData::mayGoOutAutomatically() ? '' : ' Hinweis: Der Text der Rückfrage ist noch eine Arbeitsfassung (So arbeite ich › Dokumente); mit „Senden“ bestätigen Sie ihn für diesen Vorgang.');
|
||||||
|
})
|
||||||
|
->modalSubmitActionLabel('Senden')
|
||||||
|
->action(function (RequestCaseData $requests): void {
|
||||||
|
$request = $this->record->openDataRequest();
|
||||||
|
$sent = $request !== null && $requests->approve($request);
|
||||||
|
$this->record->refresh();
|
||||||
|
$sent
|
||||||
|
? Notification::make()->title('Rückfrage gesendet')->success()->send()
|
||||||
|
: Notification::make()->title('Nicht gesendet')->body('Bitte die E-Mail-Adresse des Gastes prüfen – oder es fehlt inzwischen nichts mehr.')->danger()->send();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function stopDataRequestAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('stopDataRequest')
|
||||||
|
->label('Rückfrage beenden')
|
||||||
|
->icon(Heroicon::OutlinedNoSymbol)
|
||||||
|
->color('gray')
|
||||||
|
->visible(fn (): bool => $this->record->openDataRequest() !== null)
|
||||||
|
->requiresConfirmation()
|
||||||
|
->modalDescription('Es gehen keine Erinnerungen und Folgefragen mehr hinaus. Die fehlenden Angaben tragen Sie dann selbst ein.')
|
||||||
|
->action(function (RequestCaseData $requests): void {
|
||||||
|
$requests->close($this->record->openDataRequest(), DataRequest::STOPPED, 'von Ihnen beendet');
|
||||||
|
$this->record->refresh();
|
||||||
|
Notification::make()->title('Rückfrage beendet')->success()->send();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private function requestContactAction(): Action
|
private function requestContactAction(): Action
|
||||||
{
|
{
|
||||||
return Action::make('requestContact')
|
return Action::make('requestContact')
|
||||||
@@ -354,6 +499,50 @@ private function confirmAction(): Action
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V2.1: the landlord states that the portal confirmed the booking (e.g. seen in the portal's own interface). The steps that
|
||||||
|
* wait for it go on; the booking itself was binding from the start.
|
||||||
|
*/
|
||||||
|
private function confirmPortalAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('confirmPortal')
|
||||||
|
->label('Bestätigung des Portals festhalten')
|
||||||
|
->icon(Heroicon::OutlinedCheckBadge)
|
||||||
|
->visible(fn (): bool => $this->record->isBinding() && $this->record->process()->awaitsPortalConfirmation() && PortalConfirmation::evidence($this->record) === null)
|
||||||
|
->modalDescription('Das Portal hat die Buchung bestätigt (z. B. in seiner Oberfläche gesehen). Unterlagen und Nachrichten, die darauf warten, gehen dann weiter. Die Buchung bleibt wie sie ist.')
|
||||||
|
->schema([Textarea::make('note')->label('Woran haben Sie das gesehen?')->rows(2)->maxLength(500)])
|
||||||
|
->action(function (array $data): void {
|
||||||
|
PortalConfirmation::confirm($this->record, CaseLog::actor(), $data['note'] ?? null);
|
||||||
|
app(ProcessRunner::class)->advance($this->record->fresh(), 'portal.mail');
|
||||||
|
$this->record->refresh();
|
||||||
|
Notification::make()->title('Bestätigung festgehalten')->success()->send();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V2.1: the short booking information to the guest, sent by hand (also where the automatic dispatch is off).
|
||||||
|
*/
|
||||||
|
private function sendBookingNoticeAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('sendBookingNotice')
|
||||||
|
->label('Buchungsinformation an den Gast senden')
|
||||||
|
->icon(Heroicon::OutlinedEnvelope)
|
||||||
|
->visible(fn (): bool => $this->record->isBinding() && $this->record->process()->bookingNotice() !== BookingNoticeMode::Off && ! SendBookingNotice::sent($this->record) && filled($this->record->guest?->email))
|
||||||
|
->requiresConfirmation()
|
||||||
|
->modalDescription('Der Gast erhält eine kurze Information über seine Buchung – ohne Vertrag.')
|
||||||
|
->action(function (SendBookingNotice $notice): void {
|
||||||
|
try {
|
||||||
|
$notice->handle($this->record->fresh());
|
||||||
|
} catch (ReservationException $exception) {
|
||||||
|
Notification::make()->title('Nicht gesendet')->body($exception->getMessage())->danger()->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$this->record->refresh();
|
||||||
|
Notification::make()->title('Buchungsinformation gesendet')->success()->send();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private function resendConfirmationAction(): Action
|
private function resendConfirmationAction(): Action
|
||||||
{
|
{
|
||||||
return Action::make('resendConfirmation')
|
return Action::make('resendConfirmation')
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\Bookings\RelationManagers;
|
||||||
|
|
||||||
|
use App\Models\InboundMessage;
|
||||||
|
use Filament\Actions\Action;
|
||||||
|
use Filament\Infolists\Components\TextEntry;
|
||||||
|
use Filament\Resources\RelationManagers\RelationManager;
|
||||||
|
use Filament\Support\Icons\Heroicon;
|
||||||
|
use Filament\Tables\Columns\IconColumn;
|
||||||
|
use Filament\Tables\Columns\TextColumn;
|
||||||
|
use Filament\Tables\Table;
|
||||||
|
use Illuminate\Support\HtmlString;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Communication log, incoming side (v0.11): every e-mail of the guest or the portal that the inbox assigned to this
|
||||||
|
* case, with what the evaluation found.
|
||||||
|
*/
|
||||||
|
class InboundMessagesRelationManager extends RelationManager
|
||||||
|
{
|
||||||
|
protected static string $relationship = 'inboundMessages';
|
||||||
|
|
||||||
|
protected static ?string $title = 'Eingegangene E-Mails';
|
||||||
|
|
||||||
|
public function isReadOnly(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function table(Table $table): Table
|
||||||
|
{
|
||||||
|
return $table
|
||||||
|
->recordTitleAttribute('subject')
|
||||||
|
->defaultSort('received_at', 'desc')
|
||||||
|
->emptyStateHeading('Noch keine eingegangenen E-Mails zu diesem Vorgang')
|
||||||
|
->description('Antworten und Nachrichten aus dem Postfach für die Gästekommunikation, die diesem Vorgang zugeordnet sind. Nicht zugeordnete Nachrichten stehen unter Verwaltung › Posteingang.')
|
||||||
|
->columns([
|
||||||
|
TextColumn::make('received_at')->label('Eingang')->dateTime('d.m.Y, H:i'),
|
||||||
|
TextColumn::make('from_address')->label('Von')->description(fn (InboundMessage $record): ?string => $record->from_name),
|
||||||
|
TextColumn::make('subject')->label('Betreff')->wrap(),
|
||||||
|
TextColumn::make('extraction_status')->label('Auswertung')->badge()->formatStateUsing(fn (?string $state): string => match ($state) {
|
||||||
|
'done' => 'ausgewertet',
|
||||||
|
'failed' => 'nicht möglich',
|
||||||
|
'disabled' => 'ohne KI',
|
||||||
|
default => 'ausstehend',
|
||||||
|
}),
|
||||||
|
IconColumn::make('test_mode')->label('Testbetrieb')->boolean()->trueIcon(Heroicon::OutlinedBeaker)->falseIcon(null),
|
||||||
|
])
|
||||||
|
->recordActions([
|
||||||
|
Action::make('read')->label('Lesen')->icon(Heroicon::OutlinedEye)
|
||||||
|
->modalHeading(fn (InboundMessage $record): string => (string) $record->subject)
|
||||||
|
->modalSubmitAction(false)->modalCancelActionLabel('Schließen')->modalWidth('3xl')
|
||||||
|
->schema([
|
||||||
|
TextEntry::make('found')->label('Erkannt')->state(fn (InboundMessage $record): string => collect([...(array) ($record->extraction['applied'] ?? []), ...(array) ($record->extraction['proposed'] ?? [])])
|
||||||
|
->map(fn (array $fact): string => $fact['field'].': „'.$fact['value'].'“')->implode(' · ') ?: '–'),
|
||||||
|
TextEntry::make('body_text')->label('Nachricht')->state(fn (InboundMessage $record): HtmlString => new HtmlString(nl2br(e((string) $record->body)))),
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,7 +13,7 @@ class MessagesRelationManager extends RelationManager
|
|||||||
{
|
{
|
||||||
protected static string $relationship = 'messages';
|
protected static string $relationship = 'messages';
|
||||||
|
|
||||||
protected static ?string $title = 'Mailverlauf';
|
protected static ?string $title = 'Gesendete E-Mails';
|
||||||
|
|
||||||
public function isReadOnly(): bool
|
public function isReadOnly(): bool
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
use App\Models\Channel;
|
use App\Models\Channel;
|
||||||
use App\Models\Extra;
|
use App\Models\Extra;
|
||||||
use App\Models\Property;
|
use App\Models\Property;
|
||||||
|
use App\Support\Countries;
|
||||||
use App\Support\CurrentProperty;
|
use App\Support\CurrentProperty;
|
||||||
use App\Support\Money;
|
use App\Support\Money;
|
||||||
use Filament\Forms\Components\DatePicker;
|
use Filament\Forms\Components\DatePicker;
|
||||||
@@ -120,7 +121,7 @@ public static function configure(Schema $schema): Schema
|
|||||||
Select::make('channel_id')
|
Select::make('channel_id')
|
||||||
->label(fn (Get $get): string => $get('kind') === self::EXTERNAL ? 'Gebucht über' : 'Über ein Portal (optional)')
|
->label(fn (Get $get): string => $get('kind') === self::EXTERNAL ? 'Gebucht über' : 'Über ein Portal (optional)')
|
||||||
->placeholder('Direkt – kein Portal')
|
->placeholder('Direkt – kein Portal')
|
||||||
->options(fn (Get $get): array => Channel::query()->where('property_id', $get('property_id'))->orderBy('name')->pluck('name', 'id')->all())
|
->options(fn (Get $get): array => Channel::query()->portals()->where('property_id', $get('property_id'))->orderBy('name')->pluck('name', 'id')->all())
|
||||||
->required($is(self::EXTERNAL)),
|
->required($is(self::EXTERNAL)),
|
||||||
TextInput::make('portal_reference')->label('Buchungsnummer im Portal')->maxLength(100)->visible($is(self::EXTERNAL)),
|
TextInput::make('portal_reference')->label('Buchungsnummer im Portal')->maxLength(100)->visible($is(self::EXTERNAL)),
|
||||||
EuroInput::make('portal_total')
|
EuroInput::make('portal_total')
|
||||||
@@ -140,6 +141,7 @@ public static function configure(Schema $schema): Schema
|
|||||||
TextInput::make('street')->label('Straße')->maxLength(255),
|
TextInput::make('street')->label('Straße')->maxLength(255),
|
||||||
TextInput::make('postal_code')->label('PLZ')->maxLength(20),
|
TextInput::make('postal_code')->label('PLZ')->maxLength(20),
|
||||||
TextInput::make('city')->label('Ort')->maxLength(255),
|
TextInput::make('city')->label('Ort')->maxLength(255),
|
||||||
|
Select::make('country')->label('Land')->options(Countries::options())->placeholder('nicht bekannt'),
|
||||||
Toggle::make('guest_confirmed')->label('Der Gast hat die Buchung bereits per E-Mail bestätigt')->visible($is(self::EXTERNAL)),
|
Toggle::make('guest_confirmed')->label('Der Gast hat die Buchung bereits per E-Mail bestätigt')->visible($is(self::EXTERNAL)),
|
||||||
]),
|
]),
|
||||||
Section::make('Wie geht es weiter?')
|
Section::make('Wie geht es weiter?')
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
use App\Pricing\CaseMoney;
|
use App\Pricing\CaseMoney;
|
||||||
use App\Process\CaseActivities;
|
use App\Process\CaseActivities;
|
||||||
use App\Process\CaseAutomation;
|
use App\Process\CaseAutomation;
|
||||||
|
use App\Process\ProcessCatalogue;
|
||||||
|
use App\Process\ProcessPlan;
|
||||||
use App\Process\ProcessProfile;
|
use App\Process\ProcessProfile;
|
||||||
use App\Support\Money;
|
use App\Support\Money;
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
@@ -50,7 +52,7 @@ public static function configure(Schema $schema): Schema
|
|||||||
->columnSpan(2)
|
->columnSpan(2)
|
||||||
->schema([
|
->schema([
|
||||||
Section::make('Ablauf')
|
Section::make('Ablauf')
|
||||||
->description('Was erledigt ist, was wartet und was noch kommt.')
|
->description('Was erledigt ist, was wartet und was noch kommt. Ein Klick auf einen Schritt zeigt, was dort geschah und woher die Angaben stammen.')
|
||||||
->schema([TextEntry::make('activities')->hiddenLabel()->state(fn (Booking $record): HtmlString => self::activities($record))->html()]),
|
->schema([TextEntry::make('activities')->hiddenLabel()->state(fn (Booking $record): HtmlString => self::activities($record))->html()]),
|
||||||
Section::make('Preis und Zahlungen')
|
Section::make('Preis und Zahlungen')
|
||||||
->schema([
|
->schema([
|
||||||
@@ -121,6 +123,7 @@ public static function configure(Schema $schema): Schema
|
|||||||
->schema([
|
->schema([
|
||||||
TextEntry::make('status')->label('Status')->badge(),
|
TextEntry::make('status')->label('Status')->badge(),
|
||||||
TextEntry::make('case_type')->label('Vorgangsart')->state(fn (Booking $record): string => strtoupper($record->caseType()->value).' – '.$record->caseType()->getLabel()),
|
TextEntry::make('case_type')->label('Vorgangsart')->state(fn (Booking $record): string => strtoupper($record->caseType()->value).' – '.$record->caseType()->getLabel()),
|
||||||
|
TextEntry::make('templates')->label('Funktionsschablonen')->state(fn (Booking $record): ?string => self::templates($record))->placeholder('– (fester Ablauf)'),
|
||||||
TextEntry::make('intake')->label('Eingangsart')->state(fn (Booking $record): string => $record->intake?->getLabel() ?? '–'),
|
TextEntry::make('intake')->label('Eingangsart')->state(fn (Booking $record): string => $record->intake?->getLabel() ?? '–'),
|
||||||
TextEntry::make('sources')->label('Quellen und Kalenderdarstellungen')->state(fn (Booking $record): HtmlString => self::sources($record))->html()->columnSpanFull(),
|
TextEntry::make('sources')->label('Quellen und Kalenderdarstellungen')->state(fn (Booking $record): HtmlString => self::sources($record))->html()->columnSpanFull(),
|
||||||
TextEntry::make('profile')->label('Abwicklungsprofil (eingefroren)')->state(fn (Booking $record): HtmlString => self::profile($record))->html()->columnSpanFull(),
|
TextEntry::make('profile')->label('Abwicklungsprofil (eingefroren)')->state(fn (Booking $record): HtmlString => self::profile($record))->html()->columnSpanFull(),
|
||||||
@@ -151,7 +154,7 @@ private static function nextStep(Booking $booking): HtmlString
|
|||||||
default => 'Nichts zu tun.',
|
default => 'Nichts zu tun.',
|
||||||
};
|
};
|
||||||
$color = $next?->state === ActivityState::Problem ? '#dc2626' : ($next !== null ? '#b45309' : '#15803d');
|
$color = $next?->state === ActivityState::Problem ? '#dc2626' : ($next !== null ? '#b45309' : '#15803d');
|
||||||
$detail = $next?->detail ?? $waiting?->detail;
|
$detail = $next !== null ? $next->detail : $waiting?->detail;
|
||||||
$mode = $automatic
|
$mode = $automatic
|
||||||
? 'Dieser Vorgang läuft automatisch weiter, sobald alle Angaben da sind.'.(($blockers = self::blockers($booking)) !== [] ? ' Es fehlt: '.e(implode(' ', $blockers)) : '')
|
? 'Dieser Vorgang läuft automatisch weiter, sobald alle Angaben da sind.'.(($blockers = self::blockers($booking)) !== [] ? ' Es fehlt: '.e(implode(' ', $blockers)) : '')
|
||||||
: 'Sie geben jeden Schritt selbst frei. Der Knopf oben rechts führt zum nächsten Schritt.';
|
: 'Sie geben jeden Schritt selbst frei. Der Knopf oben rechts führt zum nächsten Schritt.';
|
||||||
@@ -217,7 +220,8 @@ private static function activities(Booking $booking): HtmlString
|
|||||||
$color = $colors[$activity->state->getColor()];
|
$color = $colors[$activity->state->getColor()];
|
||||||
$strong = $activity->state->needsAction() ? 'font-weight:700' : '';
|
$strong = $activity->state->needsAction() ? 'font-weight:700' : '';
|
||||||
|
|
||||||
return '<li style="display:flex;gap:.75rem;padding:.45rem 0;border-bottom:1px solid rgba(128,128,128,.2)">'
|
// A click opens what lies behind the step (ViewBooking::activityDetailsAction).
|
||||||
|
return '<li style="display:flex;gap:.75rem;padding:.45rem 0;border-bottom:1px solid rgba(128,128,128,.2);cursor:pointer" title="Einzelheiten ansehen" wire:click="mountAction('activityDetails', { key: ''.e($activity->key).'' })">'
|
||||||
.'<span style="width:1.4rem;text-align:center;font-weight:700;color:'.$color.'">'.$activity->state->icon().'</span>'
|
.'<span style="width:1.4rem;text-align:center;font-weight:700;color:'.$color.'">'.$activity->state->icon().'</span>'
|
||||||
.'<span style="flex:1;'.$strong.'">'.e($activity->label)
|
.'<span style="flex:1;'.$strong.'">'.e($activity->label)
|
||||||
.($activity->detail ? ' <span style="font-weight:400;color:#6b7280">· '.e($activity->detail).'</span>' : '')
|
.($activity->detail ? ' <span style="font-weight:400;color:#6b7280">· '.e($activity->detail).'</span>' : '')
|
||||||
@@ -237,6 +241,17 @@ private static function history(Booking $booking): HtmlString
|
|||||||
return new HtmlString($rows === '' ? 'Noch keine Einträge.' : '<ul style="list-style:none;padding:0;margin:0;font-size:.9rem">'.$rows.'</ul>');
|
return new HtmlString($rows === '' ? 'Noch keine Einträge.' : '<ul style="list-style:none;padding:0;margin:0;font-size:.9rem">'.$rows.'</ul>');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The function templates the case was composed with, as frozen in its plan (null for the fixed models).
|
||||||
|
*/
|
||||||
|
private static function templates(Booking $record): ?string
|
||||||
|
{
|
||||||
|
$catalogue = app(ProcessCatalogue::class);
|
||||||
|
$labels = array_map(fn (string $reference): string => ($class = $catalogue->templateClass($reference)) !== null ? $class::label().' ('.$reference.')' : $reference, ProcessPlan::of($record)->templates);
|
||||||
|
|
||||||
|
return $labels === [] ? null : implode(' · ', $labels);
|
||||||
|
}
|
||||||
|
|
||||||
private static function profile(Booking $booking): HtmlString
|
private static function profile(Booking $booking): HtmlString
|
||||||
{
|
{
|
||||||
$profile = $booking->process();
|
$profile = $booking->process();
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ public static function configure(Table $table, ?int $guestId = null): Table
|
|||||||
...collect(BookingStatus::cases())->mapWithKeys(fn (BookingStatus $status): array => [$status->value => $status->getLabel()])->all(),
|
...collect(BookingStatus::cases())->mapWithKeys(fn (BookingStatus $status): array => [$status->value => $status->getLabel()])->all(),
|
||||||
'imported' => 'Im Portalkalender geführt', 'archived' => 'Nicht mehr im Kalenderfeed',
|
'imported' => 'Im Portalkalender geführt', 'archived' => 'Nicht mehr im Kalenderfeed',
|
||||||
]),
|
]),
|
||||||
SelectFilter::make('channel')->label('Buchungskanal')->options(fn (): array => Channel::query()->orderBy('name')->pluck('name', 'id')->all()),
|
SelectFilter::make('channel')->label('Buchungskanal')->options(fn (): array => Channel::query()->portals()->orderBy('name')->pluck('name', 'id')->all()),
|
||||||
Filter::make('period')->label('Anreise im Zeitraum')->schema([
|
Filter::make('period')->label('Anreise im Zeitraum')->schema([
|
||||||
DatePicker::make('arrival_from')->label('Anreise ab'),
|
DatePicker::make('arrival_from')->label('Anreise ab'),
|
||||||
DatePicker::make('arrival_until')->label('Anreise bis'),
|
DatePicker::make('arrival_until')->label('Anreise bis'),
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
use App\Filament\Concerns\FollowsAdminMode;
|
use App\Filament\Concerns\FollowsAdminMode;
|
||||||
use App\Filament\Concerns\SelectsRecordProperty;
|
use App\Filament\Concerns\SelectsRecordProperty;
|
||||||
|
use App\Filament\Resources\Channels\Pages\ChannelProcess;
|
||||||
|
use App\Filament\Resources\Channels\Pages\ChannelProcessTest;
|
||||||
use App\Filament\Resources\Channels\Pages\ChannelRules;
|
use App\Filament\Resources\Channels\Pages\ChannelRules;
|
||||||
use App\Filament\Resources\Channels\Pages\CreateChannel;
|
use App\Filament\Resources\Channels\Pages\CreateChannel;
|
||||||
use App\Filament\Resources\Channels\Pages\EditChannel;
|
use App\Filament\Resources\Channels\Pages\EditChannel;
|
||||||
@@ -29,11 +31,11 @@ class ChannelResource extends Resource
|
|||||||
|
|
||||||
protected static string|UnitEnum|null $navigationGroup = 'Einrichtung';
|
protected static string|UnitEnum|null $navigationGroup = 'Einrichtung';
|
||||||
|
|
||||||
protected static ?string $navigationLabel = 'Kalenderabgleich (iCal)';
|
protected static ?string $navigationLabel = 'Kanäle';
|
||||||
|
|
||||||
protected static ?string $modelLabel = 'iCal-Verbindung';
|
protected static ?string $modelLabel = 'Kanal';
|
||||||
|
|
||||||
protected static ?string $pluralModelLabel = 'Kalenderabgleich (iCal)';
|
protected static ?string $pluralModelLabel = 'Kanäle (Webseite, Portale, iCal)';
|
||||||
|
|
||||||
protected static ?int $navigationSort = 4;
|
protected static ?int $navigationSort = 4;
|
||||||
|
|
||||||
@@ -61,6 +63,8 @@ public static function getPages(): array
|
|||||||
'create' => CreateChannel::route('/create'),
|
'create' => CreateChannel::route('/create'),
|
||||||
'edit' => EditChannel::route('/{record}/edit'),
|
'edit' => EditChannel::route('/{record}/edit'),
|
||||||
'rules' => ChannelRules::route('/{record}/rules'),
|
'rules' => ChannelRules::route('/{record}/rules'),
|
||||||
|
'process' => ChannelProcess::route('/{record}/process'),
|
||||||
|
'test' => ChannelProcessTest::route('/{record}/test'),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,619 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\Channels\Pages;
|
||||||
|
|
||||||
|
use App\Actions\ConfigureChannelProcess;
|
||||||
|
use App\Communication\CommunicationRules;
|
||||||
|
use App\Enums\AdminMode;
|
||||||
|
use App\Enums\Execution;
|
||||||
|
use App\Enums\IntakeKind;
|
||||||
|
use App\Enums\Medium;
|
||||||
|
use App\Enums\MessageEffect;
|
||||||
|
use App\Enums\MessageIntent;
|
||||||
|
use App\Enums\ProcessSetting;
|
||||||
|
use App\Filament\Resources\Channels\ChannelResource;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\Channel;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Process\Capability;
|
||||||
|
use App\Process\ChannelCapabilities;
|
||||||
|
use App\Process\ChannelProcessConfiguration;
|
||||||
|
use App\Process\ConfigurationImpact;
|
||||||
|
use App\Process\Models\ProcessModel;
|
||||||
|
use App\Process\ProcessBlocks;
|
||||||
|
use App\Process\ProcessCatalogue;
|
||||||
|
use App\Process\ProcessLanes;
|
||||||
|
use App\Process\ProcessProfile;
|
||||||
|
use App\Process\ProcessSettings;
|
||||||
|
use App\Process\Restriction;
|
||||||
|
use App\Process\Templates\FunctionTemplate;
|
||||||
|
use App\Process\Templates\TemplateArea;
|
||||||
|
use App\Process\Templates\TemplateComposer;
|
||||||
|
use Filament\Actions\Action;
|
||||||
|
use Filament\Notifications\Notification;
|
||||||
|
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
|
||||||
|
use Filament\Resources\Pages\Page;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Kanal › Ablauf (docs/Prozessarchitektur/Architektur/03): per intake kind of the channel the landlord chooses an
|
||||||
|
* admissible process model and sets up its steps right where they are – switch, mode, who carries it out, deadlines –
|
||||||
|
* with the inherited value and its origin, the consequences in a live preview and a test of the (unsaved) draft in the
|
||||||
|
* process tester. Saving goes through ConfigureChannelProcess; running cases keep their frozen plan (E3).
|
||||||
|
*
|
||||||
|
* @property Channel $record
|
||||||
|
*/
|
||||||
|
class ChannelProcess extends Page
|
||||||
|
{
|
||||||
|
use InteractsWithRecord;
|
||||||
|
|
||||||
|
protected static string $resource = ChannelResource::class;
|
||||||
|
|
||||||
|
protected static ?string $title = 'Ablauf';
|
||||||
|
|
||||||
|
protected string $view = 'filament.resources.channels.channel-process';
|
||||||
|
|
||||||
|
public string $intake = 'inquiry';
|
||||||
|
|
||||||
|
/** @var array<string, array{model: string, variant: string, steps: array<string, array{on?: bool}>, settings: array<string, mixed>, templates: array<string, string>}> */
|
||||||
|
public array $drafts = [];
|
||||||
|
|
||||||
|
/** @var array<string, string> capability key => '1' | '0' | '' (unknown); saving confirms what is shown */
|
||||||
|
public array $capabilityDraft = [];
|
||||||
|
|
||||||
|
/** The landlord confirmed that stored settings the chosen model overrides are removed. */
|
||||||
|
public bool $acknowledge = false;
|
||||||
|
|
||||||
|
/** The business block opened in the detail panel ('' = none). */
|
||||||
|
public string $block = '';
|
||||||
|
|
||||||
|
public function mount(int|string $record): void
|
||||||
|
{
|
||||||
|
$this->record = $this->resolveRecord($record);
|
||||||
|
$configuration = app(ChannelProcessConfiguration::class);
|
||||||
|
foreach ($configuration->intakes($this->record) as $intake) {
|
||||||
|
$this->drafts[$intake->value] = $this->storedDraft($intake);
|
||||||
|
}
|
||||||
|
$this->intake = (string) array_key_first($this->drafts);
|
||||||
|
$this->block = '';
|
||||||
|
$this->capabilityDraft = $this->storedCapabilities();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The draft as it is stored (or derived) now – the reference for "unsaved changes" and for discarding them.
|
||||||
|
* The current (saved or derived) model stays selected even if it is not admissible: the page explains why instead of
|
||||||
|
* switching silently to another one.
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
private function storedDraft(IntakeKind $intake): array
|
||||||
|
{
|
||||||
|
$current = app(ChannelProcessConfiguration::class)->current($this->record, $intake);
|
||||||
|
$stored = (array) (($this->record->process_overrides ?? [])[$intake->value] ?? []);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'model' => $current['model'],
|
||||||
|
'variant' => $current['variant'],
|
||||||
|
'steps' => (array) ($stored['steps'] ?? []),
|
||||||
|
'templates' => (array) ($stored['templates'] ?? []),
|
||||||
|
'settings' => array_map(fn (mixed $value): mixed => is_bool($value) ? ($value ? '1' : '0') : $value, array_intersect_key($stored, array_flip(array_map(fn (ProcessSetting $setting): string => $setting->value, ProcessSetting::cases())))),
|
||||||
|
'derived' => $current['derived'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
private function storedCapabilities(): array
|
||||||
|
{
|
||||||
|
return $this->record->isWebsite() ? [] : collect(app(ChannelCapabilities::class)->resolve($this->record))
|
||||||
|
->map(fn (Capability $capability): string => $capability->value === null ? '' : ($capability->value ? '1' : '0'))->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the draft of the current intake kind differs from what is stored (nothing is saved by looking or selecting).
|
||||||
|
*/
|
||||||
|
public function dirty(): bool
|
||||||
|
{
|
||||||
|
$normalise = fn (array $draft): array => [
|
||||||
|
'model' => $draft['model'],
|
||||||
|
'variant' => $draft['variant'],
|
||||||
|
'steps' => array_filter((array) $draft['steps']),
|
||||||
|
'templates' => (array) $draft['templates'],
|
||||||
|
'settings' => array_filter((array) $draft['settings'], fn (mixed $value): bool => $value !== null && $value !== ''),
|
||||||
|
];
|
||||||
|
|
||||||
|
return $normalise($this->drafts[$this->intake]) != $normalise($this->storedDraft(IntakeKind::from($this->intake)))
|
||||||
|
|| $this->capabilityDraft != $this->storedCapabilities();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throws the unsaved changes away and shows the stored configuration again.
|
||||||
|
*/
|
||||||
|
public function discard(): void
|
||||||
|
{
|
||||||
|
$intake = $this->intake;
|
||||||
|
$this->acknowledge = false;
|
||||||
|
$this->mount($this->record->getKey());
|
||||||
|
$this->intake = $intake;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function selectBlock(string $block): void
|
||||||
|
{
|
||||||
|
$this->block = $this->block === $block ? '' : $block;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updatedIntake(): void
|
||||||
|
{
|
||||||
|
$this->block = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The draft of the current intake kind including the capabilities shown (they decide which models fit).
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
private function draft(): array
|
||||||
|
{
|
||||||
|
return [...$this->drafts[$this->intake], 'capabilities' => $this->capabilityDraft];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, Capability>
|
||||||
|
*/
|
||||||
|
public function capabilities(): array
|
||||||
|
{
|
||||||
|
return app(ChannelCapabilities::class)->resolve($this->record, $this->capabilityDraft);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getTitle(): string
|
||||||
|
{
|
||||||
|
return 'Ablauf: '.$this->record->name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function expert(): bool
|
||||||
|
{
|
||||||
|
$user = auth()->user();
|
||||||
|
|
||||||
|
return ! $user instanceof User || $user->adminMode() === AdminMode::Expert;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, string> intake value => tab label
|
||||||
|
*/
|
||||||
|
public function tabs(): array
|
||||||
|
{
|
||||||
|
return collect(array_keys($this->drafts))->mapWithKeys(fn (string $intake): array => [$intake => $intake === IntakeKind::Booking->value ? 'Feste Buchungen' : 'Anfragen'])->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function question(): string
|
||||||
|
{
|
||||||
|
return $this->intake === IntakeKind::Booking->value
|
||||||
|
? 'Wie wird eine feste Buchung über '.$this->record->name.' abgewickelt?'
|
||||||
|
: 'Wie wird eine Anfrage über '.$this->record->name.' abgewickelt?';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every model of this intake kind with whether the channel fits it and why not.
|
||||||
|
*
|
||||||
|
* @return array<string, array{model: ProcessModel, admissible: bool, restrictions: list<Restriction>, hints: list<string>}>
|
||||||
|
*/
|
||||||
|
public function models(): array
|
||||||
|
{
|
||||||
|
return app(ChannelProcessConfiguration::class)->modelOptions($this->record, IntakeKind::from($this->intake), $this->capabilityDraft);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stored settings the chosen model would silently override.
|
||||||
|
*
|
||||||
|
* @return list<array{setting: ProcessSetting, stored: string, fixed: string, text: string}>
|
||||||
|
*/
|
||||||
|
public function conflicts(): array
|
||||||
|
{
|
||||||
|
return app(ChannelProcessConfiguration::class)->conflicts($this->record, IntakeKind::from($this->intake), $this->drafts[$this->intake]['model'], $this->drafts[$this->intake]['templates']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The models offered as a choice: the archetypes A3–A5 are presets of the base process, so they only appear while one
|
||||||
|
* of them is the current choice (then with the hint to move to the templates).
|
||||||
|
*
|
||||||
|
* @param array<string, array{model: ProcessModel, admissible: bool, restrictions: list<Restriction>, hints: list<string>}> $models
|
||||||
|
* @return array<string, array{model: ProcessModel, admissible: bool, restrictions: list<Restriction>, hints: list<string>}>
|
||||||
|
*/
|
||||||
|
public function visibleModels(array $models): array
|
||||||
|
{
|
||||||
|
return array_filter($models, fn (array $option, string $key): bool => ! $option['model']::isLegacy() || $key === $this->drafts[$this->intake]['model'], ARRAY_FILTER_USE_BOTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the chosen model composes function templates (otherwise its course is fixed).
|
||||||
|
*/
|
||||||
|
public function composable(): bool
|
||||||
|
{
|
||||||
|
return $this->model()->slots() !== [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The business decisions of the chosen base process: per slot the templates with fit, selection and what each stands
|
||||||
|
* for. The first view of the configurator; the single steps stay below.
|
||||||
|
*
|
||||||
|
* @return list<array{area: TemplateArea, selected: ?string, options: list<array{key: string, template: class-string<FunctionTemplate>, admissible: bool, selected: bool, restrictions: list<Restriction>, hints: list<string>, unconfirmed: list<string>, modules: list<string>}>}>
|
||||||
|
*/
|
||||||
|
public function decisions(): array
|
||||||
|
{
|
||||||
|
$model = $this->model();
|
||||||
|
if ($model->slots() === []) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
$configuration = app(ChannelProcessConfiguration::class);
|
||||||
|
$catalogue = app(ProcessCatalogue::class);
|
||||||
|
$resolved = $configuration->templatesOf($model, $this->draft());
|
||||||
|
$options = $configuration->templateOptions($this->record, $model, $this->capabilityDraft);
|
||||||
|
$decisions = [];
|
||||||
|
foreach ($model->slots() as $area) {
|
||||||
|
$selected = isset($resolved[$area->value]) ? explode('@', $resolved[$area->value])[0] : null;
|
||||||
|
$decisions[] = [
|
||||||
|
'area' => $area,
|
||||||
|
'selected' => $selected,
|
||||||
|
'options' => array_values(array_map(fn (array $option, string $key): array => [
|
||||||
|
...$option,
|
||||||
|
'key' => $key,
|
||||||
|
'selected' => $key === $selected,
|
||||||
|
'modules' => array_map(fn (string $module): string => $catalogue->modules()[$module]::definition()->label, $option['template']::modules()),
|
||||||
|
], $options[$area->value] ?? [], array_keys($options[$area->value] ?? []))),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $decisions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The archetypes as known combinations (presets) the landlord can start from.
|
||||||
|
*
|
||||||
|
* @return array<string, array{label: string, templates: array<string, string>}>
|
||||||
|
*/
|
||||||
|
public function presets(): array
|
||||||
|
{
|
||||||
|
$presets = [];
|
||||||
|
foreach (app(ProcessCatalogue::class)->models() as $key => $candidate) {
|
||||||
|
if ($candidate::isLegacy() && in_array(IntakeKind::from($this->intake), $candidate::intakes(), true)) {
|
||||||
|
$presets[$key] = ['label' => $candidate::label(), 'templates' => $candidate::presetTemplates()];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $presets;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chooses the template of an area. Switches of steps that drop out of the course are removed from the draft; the
|
||||||
|
* consequences are listed by templateImpacts() before anything is saved.
|
||||||
|
*/
|
||||||
|
public function chooseTemplate(string $area, string $key): void
|
||||||
|
{
|
||||||
|
$model = $this->model();
|
||||||
|
$option = app(ChannelProcessConfiguration::class)->templateOptions($this->record, $model, $this->capabilityDraft)[$area][$key] ?? null;
|
||||||
|
if ($option === null || ! $option['admissible']) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$this->acknowledge = false;
|
||||||
|
$this->drafts[$this->intake]['templates'] = [...app(ChannelProcessConfiguration::class)->templatesOf($model, $this->draft()), $area => $key];
|
||||||
|
$this->drafts[$this->intake]['templates'] = array_map(fn (string $reference): string => explode('@', $reference)[0], $this->drafts[$this->intake]['templates']);
|
||||||
|
$modules = $model->modules($this->drafts[$this->intake]['variant'], $this->drafts[$this->intake]['templates']);
|
||||||
|
$this->drafts[$this->intake]['steps'] = array_intersect_key($this->drafts[$this->intake]['steps'], array_flip($modules));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves from a fixed archetype to the base process with the combination the archetype stands for. Switches and settings
|
||||||
|
* stay as they are; what contradicts the templates shows as a conflict that has to be confirmed.
|
||||||
|
*/
|
||||||
|
public function applyPreset(string $archetype): void
|
||||||
|
{
|
||||||
|
$presets = $this->presets();
|
||||||
|
$composedBy = isset($presets[$archetype]) ? app(ProcessCatalogue::class)->model($archetype)::composedBy() : null;
|
||||||
|
if ($composedBy === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$base = app(ProcessCatalogue::class)->model($composedBy);
|
||||||
|
$this->acknowledge = false;
|
||||||
|
$this->drafts[$this->intake]['model'] = $base::key();
|
||||||
|
$this->drafts[$this->intake]['variant'] = 'standard';
|
||||||
|
$this->drafts[$this->intake]['templates'] = $presets[$archetype]['templates'];
|
||||||
|
$this->drafts[$this->intake]['steps'] = array_intersect_key($this->drafts[$this->intake]['steps'], array_flip($base->modules('standard', $presets[$archetype]['templates'])));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The course as the runner executes it: parallel, waiting (with what for), event-driven, time-driven, not applying.
|
||||||
|
*
|
||||||
|
* @return array<string, list<array<string, mixed>>>
|
||||||
|
*/
|
||||||
|
public function lanes(): array
|
||||||
|
{
|
||||||
|
return app(ProcessLanes::class)->of($this->steps());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What arrives here and how binding it is (the start of the course).
|
||||||
|
*
|
||||||
|
* @return array{event: string, binding: string, media: list<string>}
|
||||||
|
*/
|
||||||
|
public function entry(): array
|
||||||
|
{
|
||||||
|
$rules = app(CommunicationRules::class);
|
||||||
|
$media = array_values(array_map(fn (Medium $medium): string => $medium->getLabel(), array_filter(Medium::cases(), fn (Medium $medium): bool => $rules->mediumActive($medium))));
|
||||||
|
$booking = $this->intake === IntakeKind::Booking->value;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'event' => $booking ? 'Eine feste Buchung kommt über '.$this->record->name.' an (Portalmail, Kalender).' : ($this->record->isWebsite() ? 'Ein Gast fragt über die Webseite einen Aufenthalt an.' : 'Eine Anfrage kommt über '.$this->record->name.' an.'),
|
||||||
|
'binding' => $booking ? 'Beim Portal bereits verbindlich – wir übernehmen, wir verbinden nichts neu.' : 'Unverbindlich – verbindlich wird sie durch unser Angebot und die Annahme des Gastes.',
|
||||||
|
'media' => $media,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a message does here, by its intent – the rules (not a process): a general question creates no case.
|
||||||
|
*
|
||||||
|
* @return list<array{intent: string, effects: list<string>, creates_case: bool}>
|
||||||
|
*/
|
||||||
|
public function messageRules(): array
|
||||||
|
{
|
||||||
|
$rules = app(CommunicationRules::class);
|
||||||
|
|
||||||
|
return array_map(fn (MessageIntent $intent): array => [
|
||||||
|
'intent' => $intent->getLabel(),
|
||||||
|
'effects' => array_map(fn (MessageEffect $effect): string => $effect->getLabel(), $rules->effects(Medium::Email, $intent)),
|
||||||
|
'creates_case' => false,
|
||||||
|
], MessageIntent::cases());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the draft's change of templates means (modules, responsibilities, stored switches and settings).
|
||||||
|
*
|
||||||
|
* @return list<array<string, mixed>>
|
||||||
|
*/
|
||||||
|
public function templateImpacts(): array
|
||||||
|
{
|
||||||
|
return app(ConfigurationImpact::class)->ofTemplates($this->record, IntakeKind::from($this->intake), $this->draft());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function chooseModel(string $model): void
|
||||||
|
{
|
||||||
|
if (! ($this->models()[$model]['admissible'] ?? false)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$this->acknowledge = false;
|
||||||
|
// Leaving an archetype for a model with slots keeps its combination as the starting point of the templates.
|
||||||
|
$previous = app(ProcessCatalogue::class)->model($this->drafts[$this->intake]['model']);
|
||||||
|
$this->drafts[$this->intake]['model'] = $model;
|
||||||
|
$this->drafts[$this->intake]['variant'] = 'standard';
|
||||||
|
$this->drafts[$this->intake]['templates'] = $this->model()->slots() === [] ? [] : $previous::presetTemplates();
|
||||||
|
// Switches of steps the new course still has stay; only those that have no counterpart there drop out.
|
||||||
|
$this->drafts[$this->intake]['steps'] = array_intersect_key($this->drafts[$this->intake]['steps'], array_flip($this->model()->modules('standard', $this->drafts[$this->intake]['templates'])));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function model(): ProcessModel
|
||||||
|
{
|
||||||
|
return app(ProcessCatalogue::class)->model($this->drafts[$this->intake]['model']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function profile(): ProcessProfile
|
||||||
|
{
|
||||||
|
return app(ChannelProcessConfiguration::class)->profileWith($this->record, IntakeKind::from($this->intake), $this->draft());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The business blocks of the course with what is effective in each: values and their origin, the template chosen for
|
||||||
|
* its decision, what depends on what (derived from the resolved plan, see {@see ProcessBlocks}), the steps that can
|
||||||
|
* be configured here and the fixed ones (no controls, shown as one line), gaps the template names, open problems.
|
||||||
|
*
|
||||||
|
* @return array<string, array<string, mixed>>
|
||||||
|
*/
|
||||||
|
public function blocks(): array
|
||||||
|
{
|
||||||
|
$intake = IntakeKind::from($this->intake);
|
||||||
|
$configuration = app(ChannelProcessConfiguration::class);
|
||||||
|
$profile = $this->profile();
|
||||||
|
$model = $this->model();
|
||||||
|
$rows = $configuration->preview($this->record, $intake, $this->draft());
|
||||||
|
$templates = app(TemplateComposer::class)->classes($configuration->templatesOf($model, $this->draft()));
|
||||||
|
$steps = collect($this->steps())->keyBy('module');
|
||||||
|
$conflicts = collect($this->conflicts())->map(fn (array $conflict): string => $conflict['setting']->value)->all();
|
||||||
|
$problems = $this->problems();
|
||||||
|
|
||||||
|
$blocks = [];
|
||||||
|
foreach (app(ProcessBlocks::class)->of($rows) as $key => $block) {
|
||||||
|
$template = $block['area'] === null ? null : ($templates[$block['area']->value] ?? null);
|
||||||
|
$settings = array_values(array_filter($block['settings'], fn (ProcessSetting $setting): bool => in_array($intake, $setting->channelIntakes(), true)));
|
||||||
|
$blockSteps = array_values(array_filter(array_map(fn (array $row): ?array => $steps[$row['module']] ?? null, $block['modules'])));
|
||||||
|
$configurable = array_values(array_filter($blockSteps, fn (array $step): bool => $step['on'] && ($step['optional'] || $step['mode_setting'] || ($step['performer_setting'] && count($step['performer_options']) > 1) || $step['parameters'] !== [])
|
||||||
|
|| (! $step['on'] && $step['optional'])));
|
||||||
|
$fixed = array_values(array_filter($blockSteps, fn (array $step): bool => $step['on'] && ! in_array($step, $configurable, true)));
|
||||||
|
$blocks[$key] = [...$block,
|
||||||
|
'facts' => array_map(fn (ProcessSetting $setting): array => $this->setting($setting, $profile), $settings),
|
||||||
|
'template' => $template,
|
||||||
|
'extensions' => $template === null ? [] : $template::extensions(),
|
||||||
|
'configurable' => $configurable,
|
||||||
|
'fixed' => $fixed,
|
||||||
|
'off' => array_values(array_filter($blockSteps, fn (array $step): bool => ! $step['on'])),
|
||||||
|
'attention' => count(array_filter($settings, fn (ProcessSetting $setting): bool => in_array($setting->value, $conflicts, true))),
|
||||||
|
'problems' => $this->blockProblems($problems, $block['label'], $template, $settings),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $blocks;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The problems of the draft that concern a block: they name its template or one of its settings.
|
||||||
|
*
|
||||||
|
* @param list<string> $problems
|
||||||
|
* @param class-string<FunctionTemplate>|null $template
|
||||||
|
* @param list<ProcessSetting> $settings
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
private function blockProblems(array $problems, string $label, ?string $template, array $settings): array
|
||||||
|
{
|
||||||
|
return array_values(array_filter($problems, fn (string $problem): bool => ($template !== null && str_contains($problem, $template::label()))
|
||||||
|
|| collect($settings)->contains(fn (ProcessSetting $setting): bool => str_contains($problem, $setting->question()))));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Problems of the draft that belong to no block (shown above the blocks).
|
||||||
|
*
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public function problemsOutsideBlocks(): array
|
||||||
|
{
|
||||||
|
$inBlocks = collect($this->blocks())->flatMap(fn (array $block): array => $block['problems'])->all();
|
||||||
|
|
||||||
|
return array_values(array_diff($this->problems(), $inBlocks));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The step cards: preview row + controls of each step.
|
||||||
|
*
|
||||||
|
* @return list<array<string, mixed>>
|
||||||
|
*/
|
||||||
|
public function steps(): array
|
||||||
|
{
|
||||||
|
$configuration = app(ChannelProcessConfiguration::class);
|
||||||
|
$catalogue = app(ProcessCatalogue::class);
|
||||||
|
$model = $this->model();
|
||||||
|
$profile = $this->profile();
|
||||||
|
$draft = $this->drafts[$this->intake];
|
||||||
|
|
||||||
|
$rows = $configuration->preview($this->record, IntakeKind::from($this->intake), $this->draft());
|
||||||
|
$labels = collect($rows)->mapWithKeys(fn (array $row): array => [$row['module'] => $row['label']]);
|
||||||
|
$active = collect($rows)->where('on', true)->pluck('module')->all();
|
||||||
|
|
||||||
|
return array_map(function (array $row) use ($configuration, $catalogue, $model, $profile, $labels, $active): array {
|
||||||
|
$definition = $catalogue->modules()[$row['module']]::definition();
|
||||||
|
// The view of the order is derived from the same definitions the runner uses: only dependencies present in the plan count.
|
||||||
|
$needs = collect($definition->requires)->filter(fn ($dependency): bool => $dependency->hard && in_array($dependency->module, $active, true))->map(fn ($dependency): string => $labels[$dependency->module])->values()->all();
|
||||||
|
$after = collect($definition->requires)->filter(fn ($dependency): bool => ! $dependency->hard && in_array($dependency->module, $active, true))->map(fn ($dependency): string => $labels[$dependency->module])->values()->all();
|
||||||
|
$controls = ChannelProcessConfiguration::STEP_CONTROLS[$row['module']] ?? [];
|
||||||
|
$parameters = array_values(array_filter($controls['parameters'] ?? [], fn (ProcessSetting $setting): bool => in_array(IntakeKind::from($this->intake), $setting->channelIntakes(), true) && ! $model::fixesSetting($setting) && ($this->expert() || in_array($setting, [ProcessSetting::HoldHours, ProcessSetting::DataRequestReminderHours, ProcessSetting::ArrivalInfoDaysBefore, ProcessSetting::ClarificationHoldAutoMinutes, ProcessSetting::ContractDelivery, ProcessSetting::BookingNotice, ProcessSetting::AwaitPortalConfirmation, ProcessSetting::PortalConfirmationWaitHours], true))));
|
||||||
|
|
||||||
|
return [...$row,
|
||||||
|
'purpose' => $definition->purpose,
|
||||||
|
'needs' => $needs,
|
||||||
|
'after' => $after,
|
||||||
|
'condition' => $definition->condition,
|
||||||
|
'why' => $definition->why,
|
||||||
|
'executions' => array_map(fn (Execution $execution): string => $execution->getLabel(), $definition->executions),
|
||||||
|
'triggers' => $definition->triggers,
|
||||||
|
'waits' => $definition->waits,
|
||||||
|
'optional' => $definition->isOptional(),
|
||||||
|
'version' => $catalogue->modules()[$row['module']]::version(),
|
||||||
|
'mode_setting' => isset($controls['mode']) && ! $model::fixesSetting($controls['mode']) ? $controls['mode'] : null,
|
||||||
|
'mode_options' => $configuration->modeOptions($row['module']),
|
||||||
|
'performer_setting' => isset($controls['performer']) ? $controls['performer']['setting'] : null,
|
||||||
|
'performer_options' => $configuration->performerOptions($model, $row['module']),
|
||||||
|
'parameters' => array_map(fn (ProcessSetting $setting): array => [...$this->setting($setting, $profile), 'options' => $configuration->settingOptions($setting)], $parameters),
|
||||||
|
];
|
||||||
|
}, $rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One setting with its effective value and origin (set here, by the model, inherited from where).
|
||||||
|
*
|
||||||
|
* @return array{key: string, question: string, value: string, source: string, set: bool}
|
||||||
|
*/
|
||||||
|
public function setting(ProcessSetting $setting, ProcessProfile $profile): array
|
||||||
|
{
|
||||||
|
$source = $profile->source($setting);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'key' => $setting->value,
|
||||||
|
'question' => $setting->question(),
|
||||||
|
'value' => $setting === ProcessSetting::ContractTemplate ? (string) ($profile->value($setting) ?? 'Vorlage der Wohnung') : $setting->describe($profile->value($setting)),
|
||||||
|
'source' => in_array($source, [ProcessProfile::CHANNEL, ProcessProfile::WEBSITE], true) ? 'hier gesetzt' : 'geerbt: '.ProcessProfile::sourceLabel($source),
|
||||||
|
'set' => array_key_exists($setting->value, $this->drafts[$this->intake]['settings']) && filled($this->drafts[$this->intake]['settings'][$setting->value]),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function inherit(string $setting): void
|
||||||
|
{
|
||||||
|
unset($this->drafts[$this->intake]['settings'][$setting]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function toggleStep(string $module): void
|
||||||
|
{
|
||||||
|
$on = ($this->drafts[$this->intake]['steps'][$module]['on'] ?? true) !== false;
|
||||||
|
$this->drafts[$this->intake]['steps'][$module] = ['on' => ! $on];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public function problems(): array
|
||||||
|
{
|
||||||
|
return app(ChannelProcessConfiguration::class)->problems($this->record, IntakeKind::from($this->intake), $this->draft());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the switched-off steps of the draft mean for the others (suggestions only, nothing is changed).
|
||||||
|
*
|
||||||
|
* @return list<array<string, mixed>>
|
||||||
|
*/
|
||||||
|
public function impacts(): array
|
||||||
|
{
|
||||||
|
return app(ConfigurationImpact::class)->of($this->record, IntakeKind::from($this->intake), $this->draft());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Running cases of this channel and intake kind (they keep their frozen plan).
|
||||||
|
*/
|
||||||
|
public function runningCases(): int
|
||||||
|
{
|
||||||
|
return Booking::query()
|
||||||
|
->where(fn ($query) => $query->where('origin_channel_id', $this->record->id)->orWhere('import_channel_id', $this->record->id))
|
||||||
|
->where('intake', $this->intake)
|
||||||
|
->whereNotIn('status', ['cancelled', 'declined', 'expired', 'completed'])
|
||||||
|
->count();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function save(): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$this->record = app(ConfigureChannelProcess::class)->handle($this->record, IntakeKind::from($this->intake), $this->draft(), acknowledgeConflicts: $this->acknowledge);
|
||||||
|
} catch (ValidationException $exception) {
|
||||||
|
Notification::make()->title('Nicht gespeichert')->body(collect($exception->errors())->flatten()->implode(' '))->danger()->persistent()->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$this->drafts[$this->intake]['derived'] = false;
|
||||||
|
$this->acknowledge = false;
|
||||||
|
$intake = $this->intake;
|
||||||
|
$this->mount($this->record->getKey());
|
||||||
|
$this->intake = $intake;
|
||||||
|
$running = $this->runningCases();
|
||||||
|
Notification::make()->title('Ablauf gespeichert')->body('Gilt für neue Vorgänge.'.($running > 0 ? ' '.$running.' laufende Vorgänge behalten ihren bisherigen Ablauf.' : ''))->success()->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens the process tester with the current – also unsaved – draft of this intake kind.
|
||||||
|
*/
|
||||||
|
public function test(): void
|
||||||
|
{
|
||||||
|
session()->put('process-tester.draft.'.$this->record->id.'.'.$this->intake, $this->draft());
|
||||||
|
$this->redirect(ChannelResource::getUrl('test', ['record' => $this->record, 'intake' => $this->intake]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The effective value a new case would get, for the landlord's comparison (expert view).
|
||||||
|
*/
|
||||||
|
public function standard(ProcessSetting $setting): string
|
||||||
|
{
|
||||||
|
$profile = app(ProcessSettings::class)->resolve($this->record->property, null, IntakeKind::from($this->intake));
|
||||||
|
|
||||||
|
return $setting->describe($profile->value($setting));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getHeaderActions(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Action::make('save')->label('Speichern')->action(fn () => $this->save()),
|
||||||
|
Action::make('connection')->label('Kanaldaten')->color('gray')->url(fn (): string => ChannelResource::getUrl('edit', ['record' => $this->record])),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 444 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user