Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e4e208d18 | ||
|
|
ad63db78f3 | ||
|
|
f4a435c71a | ||
|
|
154b8a434c | ||
|
|
3a039e5c50 |
No files matched your search
@@ -11,6 +11,7 @@
|
||||
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,
|
||||
@@ -79,8 +80,22 @@ public function handle(PortalMail $mail, ?Mailbox $mailbox = null): InboundMessa
|
||||
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;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Throwable;
|
||||
use Webklex\PHPIMAP\Client;
|
||||
use Webklex\PHPIMAP\ClientManager;
|
||||
use Webklex\PHPIMAP\Folder;
|
||||
use Webklex\PHPIMAP\Message;
|
||||
|
||||
/**
|
||||
@@ -70,7 +72,7 @@ public function fetch(array $senders): array
|
||||
'protocol' => 'imap',
|
||||
]);
|
||||
$client->connect();
|
||||
$folder = $client->getFolderByPath($config['folder']);
|
||||
$folder = self::folder($client, $config['folder']);
|
||||
|
||||
$mails = [];
|
||||
foreach ($senders as $sender) {
|
||||
@@ -119,7 +121,7 @@ public function fetchAll(): array
|
||||
'username' => $config['username'], 'password' => $config['password'], 'protocol' => 'imap',
|
||||
]);
|
||||
$client->connect();
|
||||
$messages = $client->getFolderByPath($config['folder'])->query()
|
||||
$messages = self::folder($client, $config['folder'])->query()
|
||||
->whereSince(CarbonImmutable::today()->subDays((int) config('fewo.mailbox.lookback_days', 3)))
|
||||
->leaveUnread()
|
||||
->get();
|
||||
@@ -140,6 +142,55 @@ public function fetchAll(): array
|
||||
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
|
||||
{
|
||||
$text = $message->getTextBody();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
use App\Models\BookingMessage;
|
||||
use App\Models\InboundMessage;
|
||||
use App\Models\Property;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
@@ -30,7 +31,9 @@ public function match(InboundMessage $message): array
|
||||
$sender = mb_strtolower(trim((string) $message->from_address));
|
||||
$text = $message->subject."\n".$message->body;
|
||||
|
||||
$references = array_values(array_filter([$message->in_reply_to, ...((array) $message->references)]));
|
||||
// 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) {
|
||||
@@ -39,8 +42,13 @@ public function match(InboundMessage $message): array
|
||||
}
|
||||
|
||||
$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' => []];
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Actions\SendDigests;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Enums\DigestSection;
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Enums\UserRole;
|
||||
@@ -13,6 +15,7 @@
|
||||
use App\Tenancy\TenantConfig;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
use BackedEnum;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\CheckboxList;
|
||||
use Filament\Forms\Components\Radio;
|
||||
@@ -30,6 +33,7 @@
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
@@ -250,14 +254,20 @@ public function form(Schema $schema): Schema
|
||||
Select::make('mailbox_encryption')
|
||||
->label('Verschlüsselung')
|
||||
->options(['ssl' => 'SSL', 'tls' => 'TLS', 'starttls' => 'STARTTLS'])
|
||||
->placeholder('SSL'),
|
||||
TextInput::make('mailbox_folder')->label('Ordner')->placeholder('INBOX')->maxLength(190),
|
||||
->placeholder('Standard (SSL)'),
|
||||
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')
|
||||
->description('Leer bedeutet: die Vorgabe des Systems gilt. Löschfristen und Bot-Schutz lassen sich verschärfen, aber nicht über die Vorgabe hinaus lockern.')
|
||||
@@ -300,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
|
||||
{
|
||||
$data = $this->form->getState();
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Filament\Resources\Bookings\Pages\CreateBooking;
|
||||
use App\Filament\Resources\Bookings\Pages\ListBookings;
|
||||
use App\Filament\Resources\Bookings\Pages\ViewBooking;
|
||||
use App\Filament\Resources\Bookings\RelationManagers\InboundMessagesRelationManager;
|
||||
use App\Filament\Resources\Bookings\RelationManagers\MessagesRelationManager;
|
||||
use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager;
|
||||
use App\Filament\Resources\Bookings\RelationManagers\TasksRelationManager;
|
||||
@@ -76,6 +77,7 @@ public static function getRelations(): array
|
||||
PaymentsRelationManager::class,
|
||||
TasksRelationManager::class,
|
||||
MessagesRelationManager::class,
|
||||
InboundMessagesRelationManager::class,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
use App\Actions\SetBookingStatus;
|
||||
use App\Documents\OfferTerms;
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\ActivityState;
|
||||
use App\Enums\AdminMode;
|
||||
use App\Enums\AmountKind;
|
||||
use App\Enums\BookingStatus;
|
||||
@@ -43,6 +44,8 @@
|
||||
use App\Models\User;
|
||||
use App\Pricing\PrivateStayPrice;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Process\Activity;
|
||||
use App\Process\ActivityDetails;
|
||||
use App\Process\CaseActivities;
|
||||
use App\Process\CaseAutomation;
|
||||
use App\Process\CaseLog;
|
||||
@@ -153,7 +156,9 @@ protected function getHeaderActions(): array
|
||||
$this->setStatusAction(),
|
||||
])->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;
|
||||
$expert = $actions->only(self::EXPERT)->values()->all();
|
||||
$more = $actions->except(self::EXPERT)->values()->all();
|
||||
@@ -293,11 +298,15 @@ private function templateFields(): array
|
||||
private function provideContactAction(): Action
|
||||
{
|
||||
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)
|
||||
->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
|
||||
->modalHeading('Kontaktdaten des Gastes')
|
||||
->modalDescription(fn (): string => 'Aus Portalnachricht, E-Mail oder Telefonat. Nur eintragen, was bekannt ist.'.$this->openFactConflicts())
|
||||
->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')
|
||||
->fillForm(fn (): array => [
|
||||
'guest' => $this->record->guest?->only(['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']) ?? [],
|
||||
@@ -348,6 +357,37 @@ private function openFactConflicts(): string
|
||||
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).
|
||||
*/
|
||||
|
||||
@@ -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 $title = 'Mailverlauf';
|
||||
protected static ?string $title = 'Gesendete E-Mails';
|
||||
|
||||
public function isReadOnly(): bool
|
||||
{
|
||||
|
||||
@@ -50,7 +50,7 @@ public static function configure(Schema $schema): Schema
|
||||
->columnSpan(2)
|
||||
->schema([
|
||||
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()]),
|
||||
Section::make('Preis und Zahlungen')
|
||||
->schema([
|
||||
@@ -217,7 +217,8 @@ private static function activities(Booking $booking): HtmlString
|
||||
$color = $colors[$activity->state->getColor()];
|
||||
$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="flex:1;'.$strong.'">'.e($activity->label)
|
||||
.($activity->detail ? ' <span style="font-weight:400;color:#6b7280">· '.e($activity->detail).'</span>' : '')
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Actions\ContributeCaseFacts;
|
||||
use App\Actions\CreateReservation;
|
||||
use App\Actions\ReceiveInboundMessage;
|
||||
use App\Actions\RequestCaseData;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
@@ -137,7 +138,15 @@ public static function table(Table $table): Table
|
||||
CaseLog::record($booking, 'mail_in', 'E-Mail von Ihnen zugeordnet: '.$record->subject);
|
||||
$requests->replyReceived($booking);
|
||||
BookingTask::openOnce($booking, BookingTaskKind::InboundReview, 'm'.$record->id, ['due_on' => today(), 'note' => '„'.mb_substr((string) $record->subject, 0, 120).'“ – im Posteingang ansehen.']);
|
||||
Notification::make()->title('Zugeordnet')->success()->send();
|
||||
app(ReceiveInboundMessage::class)->evaluate($record);
|
||||
Notification::make()->title('Zugeordnet')->body(self::evaluationSummary($record->fresh()))->success()->send();
|
||||
}),
|
||||
Action::make('evaluateAgain')->label('Erneut auswerten')->icon(Heroicon::OutlinedArrowPath)->color('gray')
|
||||
->visible(fn (InboundMessage $record): bool => $record->booking_id !== null && in_array($record->extraction_status, ['failed', 'disabled'], true))
|
||||
->action(function (InboundMessage $record): void {
|
||||
$record->update(['extraction_status' => null]);
|
||||
app(ReceiveInboundMessage::class)->evaluate($record);
|
||||
Notification::make()->title('Ausgewertet')->body(self::evaluationSummary($record->fresh()))->send();
|
||||
}),
|
||||
Action::make('createInquiry')->label('Als neue Anfrage anlegen')->icon(Heroicon::OutlinedPlus)
|
||||
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW)
|
||||
@@ -204,6 +213,22 @@ public static function table(Table $table): Table
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the evaluation of a message did, in one sentence.
|
||||
*/
|
||||
public static function evaluationSummary(InboundMessage $message): string
|
||||
{
|
||||
$applied = collect((array) ($message->extraction['applied'] ?? []))->map(fn (array $fact): string => CaseRequirements::label($fact['field']))->implode(', ');
|
||||
$proposed = count((array) ($message->extraction['proposed'] ?? []));
|
||||
|
||||
return match ($message->extraction_status) {
|
||||
'done' => ($applied !== '' ? 'Übernommen: '.$applied.'.' : 'Keine Angaben automatisch übernommen.').($proposed > 0 ? ' '.$proposed.' Vorschlag/Vorschläge zu prüfen.' : ''),
|
||||
'disabled' => 'Keine automatische Auswertung (System › KI-Anbindung nicht eingerichtet oder abgelehnt).',
|
||||
'failed' => 'Die automatische Auswertung war nicht möglich: '.($message->extraction['error'] ?? 'unbekannter Fehler'),
|
||||
default => 'Wird ausgewertet.',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Cases to assign a message to: the hints first, then the open cases.
|
||||
*
|
||||
|
||||
@@ -2,8 +2,12 @@
|
||||
|
||||
namespace App\Filament\Resources\InboundMessages\Pages;
|
||||
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Filament\Resources\InboundMessages\InboundMessageResource;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class ListInboundMessages extends ListRecords
|
||||
{
|
||||
@@ -11,6 +15,14 @@ class ListInboundMessages extends ListRecords
|
||||
|
||||
public function getSubheading(): ?string
|
||||
{
|
||||
return 'Nachrichten aus Ihrem Postfach für die Gästekommunikation. Zugeordnet wird nur über einen sicheren Bezug (Antwort auf unsere Mail, Vorgangsnummer und Absender, oder Absender mit Wohnung und Zeitraum). Alles andere wartet hier auf Sie; eine Nachricht legt nie selbst einen Vorgang an.';
|
||||
$mailbox = Settings::tenant()?->activeMailbox();
|
||||
$state = match (true) {
|
||||
$mailbox === null || blank($mailbox->host) => 'Kein Postfach eingerichtet (System › Betrieb).',
|
||||
! $mailbox->readsEverything() => 'Das Postfach liest nur Buchungsmails der Portale; für Gast-Mails „Alle Nachrichten“ wählen (System › Betrieb).',
|
||||
default => 'Abruf jede Minute, zuletzt erfolgreich: '.(($success = Cache::get(MailboxReader::key(MailboxReader::LAST_SUCCESS_KEY))) ? CarbonImmutable::parse($success)->format('d.m.Y, H:i').' Uhr' : 'noch nie')
|
||||
.(($error = Cache::get(MailboxReader::key(MailboxReader::LAST_ERROR_KEY))) ? ' · Letzter Fehler: '.mb_substr((string) $error, 0, 160) : '').'.',
|
||||
};
|
||||
|
||||
return $state.' Zugeordnet wird nur über einen sicheren Bezug (Antwort auf unsere Mail, Vorgangsnummer und Absender, oder Absender mit Wohnung und Zeitraum). Alles andere wartet hier auf Sie; eine Nachricht legt nie selbst einen Vorgang an.';
|
||||
}
|
||||
}
|
||||
@@ -519,6 +519,12 @@ public function canBeArchived(): bool
|
||||
|| ($this->departure->isPast() && in_array($this->status, BookingStatus::occupying(), true));
|
||||
}
|
||||
|
||||
/** @return HasMany<InboundMessage, $this> */
|
||||
public function inboundMessages(): HasMany
|
||||
{
|
||||
return $this->hasMany(InboundMessage::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<DataRequest, $this> */
|
||||
public function dataRequests(): HasMany
|
||||
{
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
namespace App\Process;
|
||||
|
||||
use App\Enums\FactSource;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingEvent;
|
||||
use App\Models\CaseFact;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* What lies behind one step of the case's progress list: the history entries that belong to it and – for the guest's
|
||||
* details – every detail with its source, time, evidence and certainty (v0.11, S5), so the landlord can see where a
|
||||
* value came from and correct it.
|
||||
*/
|
||||
final class ActivityDetails
|
||||
{
|
||||
/** History types per step (the step's own key or its prefix). */
|
||||
private const EVENT_TYPES = [
|
||||
'intake' => ['created', 'intake', 'profile', 'hold', 'mode'],
|
||||
'contact' => ['facts', 'fact', 'guest', 'data_request', 'mail_in'],
|
||||
'data_request' => ['data_request', 'mail_in', 'facts', 'fact'],
|
||||
'information' => ['information', 'mail', 'hold'],
|
||||
'wish' => ['wish'],
|
||||
'wish_check' => ['wish', 'status'],
|
||||
'offer' => ['offer', 'hold', 'mail', 'status'],
|
||||
'acceptance' => ['offer', 'status'],
|
||||
'binding' => ['status', 'portal_signal'],
|
||||
'price' => ['price', 'amount'],
|
||||
'documents' => ['document', 'mail'],
|
||||
'arrival_info' => ['document', 'mail'],
|
||||
'review' => ['mail'],
|
||||
'payment' => ['payment', 'amount'],
|
||||
'deposit' => ['payment'],
|
||||
'balance' => ['payment'],
|
||||
'payout' => ['payment', 'amount'],
|
||||
'change_proposed' => ['change'],
|
||||
'arrival_details' => ['task', 'services'],
|
||||
'stay' => ['task', 'services', 'status'],
|
||||
'closure' => ['task', 'status', 'settled'],
|
||||
'settlement' => ['settled'],
|
||||
'task_' => ['task'],
|
||||
];
|
||||
|
||||
public static function activity(Booking $booking, string $key): ?Activity
|
||||
{
|
||||
return collect(CaseActivities::for($booking))->first(fn (Activity $activity): bool => $activity->key === $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, BookingEvent>
|
||||
*/
|
||||
public static function events(Booking $booking, string $key): Collection
|
||||
{
|
||||
$types = self::EVENT_TYPES[$key] ?? (str_starts_with($key, 'task_') ? self::EVENT_TYPES['task_'] : []);
|
||||
|
||||
return $types === [] ? collect() : $booking->events()->whereIn('type', $types)->reorder()->latest('occurred_at')->latest('id')->limit(50)->get();
|
||||
}
|
||||
|
||||
public static function showsFacts(string $key): bool
|
||||
{
|
||||
return in_array($key, ['contact', 'data_request', 'intake'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every detail of the guest and the stay with its current value and where it came from (latest decisive fact).
|
||||
*
|
||||
* @return list<array{field: string, label: string, value: ?string, source: ?string, actor: ?string, at: ?string, evidence: ?string, confidence: ?float, open: list<string>}>
|
||||
*/
|
||||
public static function facts(Booking $booking): array
|
||||
{
|
||||
$facts = CaseFact::query()->where('booking_id', $booking->id)->orderBy('id')->get()->groupBy('field');
|
||||
$rows = [];
|
||||
|
||||
foreach ([...CaseRequirements::FIELDS, ...CaseRequirements::OPTIONAL_FIELDS] as $field => $label) {
|
||||
$value = CaseRequirements::value($booking, $field);
|
||||
/** @var Collection<int, CaseFact> $history */
|
||||
$history = $facts->get($field, collect());
|
||||
$decisive = $history->reverse()->first(fn (CaseFact $fact): bool => in_array($fact->outcome, [CaseFact::APPLIED, CaseFact::CONFIRMED], true));
|
||||
$open = $history->filter(fn (CaseFact $fact): bool => in_array($fact->outcome, [CaseFact::CONFLICT, CaseFact::CHANGE_REQUEST], true) && $fact->created_at->greaterThanOrEqualTo($decisive?->created_at ?? $fact->created_at))
|
||||
->map(fn (CaseFact $fact): string => '„'.$fact->value.'“ laut '.$fact->source->getLabel().' – '.$fact->outcomeLabel())->values()->all();
|
||||
|
||||
if (blank($value) && $history->isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
'field' => $field,
|
||||
'label' => $label,
|
||||
'value' => filled($value) ? (string) $value : null,
|
||||
'source' => $decisive?->source instanceof FactSource ? $decisive->source->getLabel() : (filled($value) ? 'vor der Herkunftsaufzeichnung erfasst' : null),
|
||||
'actor' => $decisive?->actor,
|
||||
'at' => $decisive?->created_at?->format('d.m.Y, H:i'),
|
||||
'evidence' => $decisive?->evidence,
|
||||
'confidence' => $decisive?->confidence,
|
||||
'open' => $open,
|
||||
];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
}
|
||||
@@ -125,11 +125,20 @@ public static function for(Booking $booking): array
|
||||
});
|
||||
} elseif ($inquiry) {
|
||||
$offerDone = $booking->offer_version > 0 || $binding;
|
||||
// G2a (v0.11): without every required detail there is no offer – the step waits for the guest's answer
|
||||
// (mail, link or the landlord's entry) instead of being offered as the next step.
|
||||
$offerMissing = $offerDone ? [] : CaseRequirements::missing($booking, CaseRequirements::OFFER);
|
||||
$activities[] = new Activity('offer', $booking->processingMode() === ProcessingMode::Automatic ? 'Angebot senden (automatisch)' : 'Angebot prüfen und senden', $later(match (true) {
|
||||
$offerDone => ActivityState::Done,
|
||||
$offerMissing !== [] => ActivityState::Later,
|
||||
$booking->status === BookingStatus::Reserved && filled($booking->guest?->email) => ActivityState::Open,
|
||||
default => ActivityState::Later,
|
||||
}), $booking->offer_version > 0 ? 'Version '.$booking->offer_version.' vom '.$booking->offer_sent_at?->format('d.m.Y') : ($booking->hold_expires_at ? 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr' : null), $offerDone ? null : 'sendOffer');
|
||||
}), match (true) {
|
||||
$booking->offer_version > 0 => 'Version '.$booking->offer_version.' vom '.$booking->offer_sent_at?->format('d.m.Y'),
|
||||
$offerMissing !== [] => 'erst wenn alle Angaben da sind',
|
||||
$booking->hold_expires_at !== null => 'Zeitraum reserviert bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr',
|
||||
default => null,
|
||||
}, $offerDone || $offerMissing !== [] ? null : 'sendOffer');
|
||||
|
||||
$activities[] = new Activity('acceptance', 'Gast nimmt das Angebot an', $later(match (true) {
|
||||
$binding => ActivityState::Done,
|
||||
@@ -356,6 +365,8 @@ private static function task(BookingTask $task): Activity
|
||||
$task->kind === BookingTaskKind::PayoutCheck && $task->due_on?->isAfter($today) => ActivityState::Waiting,
|
||||
$task->kind === BookingTaskKind::Service && $task->due_on?->isAfter($today) => ActivityState::Later,
|
||||
$task->kind === BookingTaskKind::BookingWish && $task->booking !== null && ! app(AvailabilityChecker::class)->isAvailable($task->booking->property, $task->booking->arrival, $task->booking->departure, ignore: $task->booking) => ActivityState::Problem,
|
||||
// v0.11 (B3): the binding confirmation waits for the missing details as well.
|
||||
$task->kind === BookingTaskKind::BookingWish && $task->booking !== null && CaseRequirements::missing($task->booking, CaseRequirements::WISH_CONFIRMATION) !== [] => ActivityState::Waiting,
|
||||
default => ActivityState::Open,
|
||||
};
|
||||
$detail = $task->status === BookingTaskStatus::Done
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<div style="display:flex;flex-direction:column;gap:1rem;font-size:.9rem">
|
||||
<div>
|
||||
<strong>{{ $activity->state->getLabel() }}</strong>@if ($activity->detail) · {{ $activity->detail }}@endif
|
||||
</div>
|
||||
|
||||
@if ($facts !== null)
|
||||
<div>
|
||||
<div style="font-weight:600;margin-bottom:.35rem">Angaben und ihre Herkunft</div>
|
||||
@if ($facts === [])
|
||||
<p style="color:#6b7280">Noch keine Angaben.</p>
|
||||
@else
|
||||
<table style="width:100%;border-collapse:collapse">
|
||||
<thead>
|
||||
<tr style="text-align:left;color:#6b7280;border-bottom:1px solid rgba(128,128,128,.3)">
|
||||
<th style="padding:.3rem .4rem">Angabe</th><th style="padding:.3rem .4rem">Wert</th><th style="padding:.3rem .4rem">Herkunft</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach ($facts as $row)
|
||||
<tr style="border-bottom:1px solid rgba(128,128,128,.2);vertical-align:top">
|
||||
<td style="padding:.3rem .4rem">{{ $row['label'] }}</td>
|
||||
<td style="padding:.3rem .4rem">{{ $row['value'] ?? '–' }}</td>
|
||||
<td style="padding:.3rem .4rem">
|
||||
{{ $row['source'] ?? '–' }}@if ($row['at']) · {{ $row['at'] }}@endif
|
||||
@if ($row['confidence'] !== null)<span style="color:#6b7280"> · Sicherheit {{ number_format($row['confidence'] * 100, 0) }} %</span>@endif
|
||||
@if ($row['evidence'])<div style="color:#6b7280">Beleg: „{{ \Illuminate\Support\Str::limit($row['evidence'], 160) }}“</div>@endif
|
||||
@foreach ($row['open'] as $open)<div style="color:#b45309">Offen: {{ $open }}</div>@endforeach
|
||||
</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
<p style="color:#6b7280;margin-top:.35rem">Stimmt etwas nicht, korrigieren Sie es mit „Angaben korrigieren“. Ihre Eingabe gilt, der vorherige Wert bleibt im Nachweis erhalten.</p>
|
||||
@endif
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<div>
|
||||
<div style="font-weight:600;margin-bottom:.35rem">Was dazu geschah</div>
|
||||
@if ($events->isEmpty())
|
||||
<p style="color:#6b7280">Keine Einträge zu diesem Schritt. Der vollständige Verlauf steht im Bereich „Verlauf“.</p>
|
||||
@else
|
||||
<ul style="list-style:none;padding:0;margin:0">
|
||||
@foreach ($events as $event)
|
||||
<li style="margin:.25rem 0"><span style="color:#6b7280">{{ $event->occurred_at->format('d.m.Y H:i') }}</span> · {{ $event->summary }}@if ($event->actor) <span style="color:#6b7280">({{ $event->actor }})</span>@endif
|
||||
@if ($event->reason)<div style="color:#6b7280;margin-left:1rem">Grund: {{ $event->reason }}</div>@endif
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
@@ -5,6 +5,7 @@
|
||||
use App\Actions\ContributeCaseFacts;
|
||||
use App\Actions\CreateReservation;
|
||||
use App\Actions\DecideBookingWish;
|
||||
use App\Actions\ProvideGuestContact;
|
||||
use App\Actions\SendInformation;
|
||||
use App\Actions\SendOffer;
|
||||
use App\Actions\SubmitBookingWish;
|
||||
@@ -15,23 +16,28 @@
|
||||
use App\Enums\DocumentKind;
|
||||
use App\Enums\FactSource;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Filament\Resources\Bookings\Pages\ViewBooking;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Models\CaseFact;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Guest;
|
||||
use App\Models\Property;
|
||||
use App\Models\User;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Process\ActivityDetails;
|
||||
use App\Process\CaseRequirements;
|
||||
use App\Support\Content;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Seeders\PropertySeeder;
|
||||
use Database\Seeders\SiteSeeder;
|
||||
use Filament\Actions\Testing\TestAction;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Livewire\Livewire;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
@@ -206,6 +212,28 @@ public function test_completing_the_address_continues_an_automatic_case(): void
|
||||
$this->assertSame(BookingStatus::OfferSent, $booking->fresh()->status);
|
||||
}
|
||||
|
||||
/** A step of the progress list shows where each detail came from and lets the landlord correct it. */
|
||||
public function test_the_progress_list_shows_the_source_of_each_detail_and_the_landlord_corrects_it(): void
|
||||
{
|
||||
$this->actingAs(User::factory()->create());
|
||||
$booking = $this->request();
|
||||
app(ContributeCaseFacts::class)->handle($booking, ['guest.street' => 'Lindenallee 12'], FactSource::Extraction, ['reference' => 'message:1', 'evidence' => ['guest.street' => 'unsere Anschrift: Lindenallee 12'], 'confidence' => ['guest.street' => 0.9]]);
|
||||
|
||||
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
|
||||
->assertSeeHtml('mountAction('activityDetails', { key: 'contact' })')
|
||||
->mountAction(TestAction::make('activityDetails')->arguments(['key' => 'contact']))
|
||||
->assertActionMounted('activityDetails')
|
||||
->assertMountedActionModalSee(['Angaben und ihre Herkunft', 'Lindenallee 12', 'aus einer Nachricht erkannt (KI)', 'Sicherheit 90 %', 'unsere Anschrift: Lindenallee 12', 'Anfrageformular der Webseite']);
|
||||
|
||||
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
|
||||
->callAction(TestAction::make('provideContact')->arguments([]), ['guest' => ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org', 'street' => 'Lindenallee 21'], 'process' => ProvideGuestContact::MANUAL, 'guest_confirmed' => false]);
|
||||
|
||||
$this->assertSame('Lindenallee 21', $booking->guest->fresh()->street);
|
||||
$row = collect(ActivityDetails::facts($booking->fresh()))->firstWhere('field', 'guest.street');
|
||||
$this->assertSame(['Lindenallee 21', 'von Ihnen eingetragen'], [$row['value'], $row['source']]);
|
||||
$this->assertSame('Lindenallee 12', CaseFact::query()->where('field', 'guest.street')->where('source', FactSource::Landlord)->sole()->previous_value, 'the corrected value stays in the evidence');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, ?string> $address
|
||||
*/
|
||||
|
||||
@@ -4,11 +4,13 @@
|
||||
|
||||
use App\Actions\ContributeCaseFacts;
|
||||
use App\Actions\CreateReservation;
|
||||
use App\Actions\ProvideGuestContact;
|
||||
use App\Actions\RequestCaseData;
|
||||
use App\Actions\TakeOverExternalBooking;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\FactSource;
|
||||
use App\Filament\Resources\Bookings\Pages\ViewBooking;
|
||||
use App\Mail\DataRequested;
|
||||
use App\Mail\ReservationReceived;
|
||||
use App\Models\Booking;
|
||||
@@ -17,6 +19,7 @@
|
||||
use App\Models\Channel;
|
||||
use App\Models\DataRequest;
|
||||
use App\Models\Property;
|
||||
use App\Models\User;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Process\CaseActivities;
|
||||
use App\Support\Content;
|
||||
@@ -24,11 +27,13 @@
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Seeders\PropertySeeder;
|
||||
use Database\Seeders\SiteSeeder;
|
||||
use Filament\Actions\Testing\TestAction;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Livewire\Livewire;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
@@ -84,6 +89,39 @@ public function test_approval_mode_prepares_the_question_and_the_landlord_releas
|
||||
$this->assertSame(DataRequest::OPEN, $request->fresh()->status);
|
||||
}
|
||||
|
||||
/** G2a: while the guest is asked, the offer is not offered as the next step – neither by hand nor automatically. */
|
||||
public function test_the_offer_waits_for_the_answer_even_when_the_steps_are_released_by_hand(): void
|
||||
{
|
||||
Settings::tenant()->update(['process_defaults' => ['processing' => 'manual', 'data_request_mode' => 'automatic']]);
|
||||
|
||||
$booking = $this->request();
|
||||
|
||||
$this->assertSame(DataRequest::OPEN, $booking->openDataRequest()->status);
|
||||
$this->assertNotSame('sendOffer', CaseActivities::next($booking)?->action);
|
||||
$offer = collect(CaseActivities::for($booking))->firstWhere('key', 'offer');
|
||||
$this->assertSame(['erst wenn alle Angaben da sind', null], [$offer->detail, $offer->action]);
|
||||
|
||||
app(ContributeCaseFacts::class)->handle($booking, ['guest.street' => 'Strandweg 1', 'guest.postal_code' => '18225', 'guest.city' => 'Kühlungsborn', 'guest.country' => 'DE'], FactSource::GuestLink, ['reference' => 'link']);
|
||||
$this->assertSame('sendOffer', CaseActivities::next($booking->fresh())?->action, 'complete: now the landlord releases the offer');
|
||||
$this->assertSame(BookingStatus::Reserved, $booking->fresh()->status, 'manual processing: nothing sent by itself');
|
||||
}
|
||||
|
||||
public function test_the_landlord_enters_the_missing_details_himself_while_the_guest_is_asked(): void
|
||||
{
|
||||
$this->actingAs(User::factory()->create());
|
||||
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'data_request_mode' => 'automatic']]);
|
||||
$booking = $this->request();
|
||||
|
||||
$page = Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]);
|
||||
$primary = $page->instance()->getCachedHeaderActions()[0];
|
||||
$this->assertSame(['provideContact', 'Fehlende Angaben selbst eintragen'], [$primary->getName(), $primary->getLabel()]);
|
||||
|
||||
$page->callAction(TestAction::make('provideContact')->arguments([]), ['guest' => ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org', 'street' => 'Strandweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'], 'process' => ProvideGuestContact::AUTOMATIC, 'guest_confirmed' => false]);
|
||||
|
||||
$this->assertSame(DataRequest::COMPLETED, $booking->dataRequests()->first()->status);
|
||||
$this->assertSame(BookingStatus::OfferSent, $booking->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_manual_mode_leaves_the_question_to_the_landlord(): void
|
||||
{
|
||||
Settings::tenant()->update(['process_defaults' => ['data_request_mode' => 'manual']]);
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
use App\Channels\Mail\PortalMail;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Filament\Pages\Operations;
|
||||
use App\Filament\Resources\Bookings\Pages\ViewBooking;
|
||||
use App\Filament\Resources\Bookings\RelationManagers\InboundMessagesRelationManager;
|
||||
use App\Filament\Resources\InboundMessages\Pages\ListInboundMessages;
|
||||
use App\Mail\DataRequested;
|
||||
use App\Models\Booking;
|
||||
@@ -33,6 +35,9 @@
|
||||
use Livewire\Livewire;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
use Webklex\PHPIMAP\Client;
|
||||
use Webklex\PHPIMAP\Folder;
|
||||
use Webklex\PHPIMAP\Support\FolderCollection;
|
||||
|
||||
/**
|
||||
* v0.11 package U5: the inbox of the guest communication mailbox – stored once, portal notifications through the
|
||||
@@ -182,6 +187,58 @@ public function test_the_mailbox_is_kept_as_a_record_and_full_mode_reads_every_m
|
||||
$this->assertNotNull($mailbox->fresh()->last_fetched_at);
|
||||
}
|
||||
|
||||
/** Test operation: every answer comes from the test mailbox, which then stands for the guest of the named case. */
|
||||
public function test_in_test_operation_the_test_address_counts_as_the_guest_of_the_named_case(): void
|
||||
{
|
||||
Settings::tenant()->update(['test_recipient' => 'test@example.org']);
|
||||
$booking = $this->request();
|
||||
|
||||
$message = $this->receive(from: 'test@example.org', subject: 'Re: Ihre Anfrage '.$booking->reference, text: 'Strandweg 1');
|
||||
|
||||
$this->assertSame([InboundMessage::ASSIGNED, $booking->id, 'reference_test_sender'], [$message->status, $message->booking_id, $message->match_reason]);
|
||||
|
||||
Settings::tenant()->update(['operating_mode' => 'live']);
|
||||
$live = $this->receive(from: 'test@example.org', subject: 'Re: Ihre Anfrage '.$booking->reference, text: 'Strandweg 1', id: '<live@x>');
|
||||
$this->assertSame(InboundMessage::NEEDS_REVIEW, $live->status, 'in live operation the test address is nobody special');
|
||||
}
|
||||
|
||||
public function test_the_mailbox_can_be_checked_and_incoming_mails_show_on_the_case(): void
|
||||
{
|
||||
$this->actingAs(User::factory()->create());
|
||||
Mailbox::query()->create(['tenant_id' => Settings::tenant()->id, 'host' => 'imap.example.org', 'username' => 'anfragen@example.org', 'password' => 'x', 'mode' => Mailbox::FULL, 'is_active' => true]);
|
||||
$reader = Mockery::mock(MailboxReader::class);
|
||||
$reader->shouldReceive('probe')->once()->andReturn(7);
|
||||
$this->app->instance(MailboxReader::class, $reader);
|
||||
|
||||
Livewire::test(Operations::class)->call('checkMailbox')->assertNotified('Verbindung in Ordnung');
|
||||
|
||||
$booking = $this->request();
|
||||
$this->receive(from: 'gesa@example.org', subject: 'Frage zu '.$booking->reference, text: 'Hallo');
|
||||
Livewire::test(InboundMessagesRelationManager::class, ['ownerRecord' => $booking, 'pageClass' => ViewBooking::class])
|
||||
->assertSee('Frage zu '.$booking->reference);
|
||||
}
|
||||
|
||||
public function test_the_inbox_is_found_under_its_web_mail_name_and_an_unknown_folder_is_explained(): void
|
||||
{
|
||||
$folder = function (string $path): Folder {
|
||||
$folder = Mockery::mock(Folder::class);
|
||||
$folder->path = $path;
|
||||
$folder->name = $path;
|
||||
|
||||
return $folder;
|
||||
};
|
||||
$client = Mockery::mock(Client::class);
|
||||
$client->shouldReceive('getFolders')->andReturn(FolderCollection::make([$folder('Trash'), $folder('Sent Items'), $folder('INBOX')]));
|
||||
|
||||
foreach (['Posteingang', '', 'inbox', 'INBOX'] as $name) {
|
||||
$this->assertSame('INBOX', MailboxReader::folder($client, $name)->path);
|
||||
}
|
||||
$this->assertSame('Sent Items', MailboxReader::folder($client, 'sent items')->path);
|
||||
|
||||
$this->expectExceptionMessage('Vorhanden: Trash, Sent Items, INBOX');
|
||||
MailboxReader::folder($client, 'Archiv');
|
||||
}
|
||||
|
||||
private function request(string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking
|
||||
{
|
||||
return app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org'])->fresh();
|
||||
|
||||
@@ -65,6 +65,7 @@ protected function setUp(): void
|
||||
TenantService::query()->create(['tenant_id' => Settings::tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true, 'api_key' => 'test-key',
|
||||
'settings' => ['provider' => 'anthropic', 'small_model' => 'claude-haiku-5-5', 'review_model' => 'claude-opus-5-5']]);
|
||||
app(TenantFeatures::class)->forget();
|
||||
Http::preventStrayRequests();
|
||||
}
|
||||
|
||||
public function test_without_the_service_nothing_is_sent_to_a_provider(): void
|
||||
|
||||
@@ -68,6 +68,7 @@ protected function setUp(): void
|
||||
TenantService::query()->create(['tenant_id' => Settings::tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true, 'api_key' => 'sk-or-test',
|
||||
'settings' => ['provider' => 'openrouter', 'small_model' => 'vendor/small-model', 'review_model' => 'vendor/large-model']]);
|
||||
app(TenantFeatures::class)->forget();
|
||||
Http::preventStrayRequests();
|
||||
}
|
||||
|
||||
public function test_from_an_incomplete_website_request_to_the_binding_booking(): void
|
||||
@@ -87,8 +88,14 @@ public function test_from_an_incomplete_website_request_to_the_binding_booking()
|
||||
$question = BookingMessage::query()->where('booking_id', $booking->id)->where('subject', 'like', '%Bitte ergänzen%')->sole();
|
||||
$this->assertSame('test', $question->audience, 'test operation: not delivered to the guest');
|
||||
|
||||
// The provider of the landlord's own AI access (faked; no network).
|
||||
$this->fakeExtraction([
|
||||
['field' => 'guest.street', 'value' => 'Lindenallee 12', 'evidence' => 'Lindenallee 12', 'confidence' => 0.97],
|
||||
['field' => 'guest.postal_code', 'value' => '10115', 'evidence' => '10115 Berlin', 'confidence' => 0.97],
|
||||
['field' => 'guest.city', 'value' => 'Berlin', 'evidence' => '10115 Berlin', 'confidence' => 0.97],
|
||||
]);
|
||||
// 3. The guest answers by e-mail; the inbox reads it, assigns it by the reply reference and stores it once.
|
||||
$reply = new PortalMail('<antwort@gast.example>', 'test@example.org', 'Re: '.$question->subject, "Hallo,\nunsere Anschrift: Lindenallee 12, 10115 Berlin, Deutschland.\nGesa", CarbonImmutable::now(), inReplyTo: $question->message_id);
|
||||
$reply = new PortalMail('<antwort@gast.example>', 'test@example.org', 'Re: '.$question->subject, "Hallo,\nunsere Anschrift: Lindenallee 12, 10115 Berlin, Deutschland.\nGesa", CarbonImmutable::now(), inReplyTo: trim((string) $question->message_id, '<>'));
|
||||
$reader = Mockery::mock(MailboxReader::class);
|
||||
$reader->shouldReceive('fetchAll')->andReturn([$reply]);
|
||||
$this->app->instance(MailboxReader::class, $reader);
|
||||
@@ -96,15 +103,11 @@ public function test_from_an_incomplete_website_request_to_the_binding_booking()
|
||||
$this->artisan('channels:fetch-mail')->assertSuccessful();
|
||||
|
||||
$message = InboundMessage::query()->sole();
|
||||
$this->assertSame([InboundMessage::ASSIGNED, $booking->id, 'reply', true], [$message->status, $message->booking_id, $message->match_reason, $message->test_mode]);
|
||||
// The server delivers the reference without angle brackets; it is assigned anyway, and evaluated at once.
|
||||
$this->assertSame([InboundMessage::PROCESSED, $booking->id, 'reply', true], [$message->status, $message->booking_id, $message->match_reason, $message->test_mode]);
|
||||
$this->assertNull($request->fresh()->next_reminder_at, 'the answer stops the reminder');
|
||||
|
||||
// 4. Extraction (faked provider) → rules → fact intake → the existing process sends the offer.
|
||||
$this->fakeExtraction([
|
||||
['field' => 'guest.street', 'value' => 'Lindenallee 12', 'evidence' => 'Lindenallee 12', 'confidence' => 0.97],
|
||||
['field' => 'guest.postal_code', 'value' => '10115', 'evidence' => '10115 Berlin', 'confidence' => 0.97],
|
||||
['field' => 'guest.city', 'value' => 'Berlin', 'evidence' => '10115 Berlin', 'confidence' => 0.97],
|
||||
]);
|
||||
// 4. The inbox evaluated the reply at once (extraction → rules → fact intake); the five-minute run finds nothing left.
|
||||
$this->artisan('messages:extract')->assertSuccessful();
|
||||
|
||||
$booking->refresh();
|
||||
|
||||
Reference in new issue
Block a user