Files
fewo-stommer/app/Filament/Resources/InboundMessages/InboundMessageResource.php
T
LarsandClaude Opus 5.5 ad63db78f3
Deploy FeWo mit PipelineManager / deploy (push) Successful in 5m6s
Posteingang: Antwortbezug ohne Klammern, Testadresse im Testbetrieb, sofortige Auswertung
- Antwortbezug (In-Reply-To/References) wird mit und ohne spitze Klammern
  verglichen – Strato liefert ihn ohne, gespeichert war er mit; Antworten
  blieben deshalb im Posteingang hängen.
- Testbetrieb: Die Testadresse steht zusammen mit der genannten
  Vorgangsnummer für den Gast dieses Vorgangs (alle Antworten kommen vom
  Testpostfach). Im Live-Betrieb gilt das nicht.
- Eine zugeordnete Nachricht wird sofort ausgewertet (automatisch und nach
  Zuordnung von Hand), nicht erst im Fünf-Minuten-Lauf; die Meldung nennt,
  was übernommen wurde. Neu: „Erneut auswerten“.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 17:39:11 +01:00

254 lines
17 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Filament\Resources\InboundMessages;
use App\Actions\ContributeCaseFacts;
use App\Actions\CreateReservation;
use App\Actions\ReceiveInboundMessage;
use App\Actions\RequestCaseData;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\FactSource;
use App\Exceptions\ReservationException;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\InboundMessages\Pages\ListInboundMessages;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\InboundMessage;
use App\Models\Property;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\CaseLog;
use App\Process\CaseRequirements;
use BackedEnum;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\HtmlString;
use UnitEnum;
/**
* The inbox of v0.11 (CH-06, "Kommunikations-Klärungsansicht"): messages of the guest communication mailbox, with
* hints from known senders. The landlord assigns a message to a case, makes a new request out of it, or ignores it.
* Nothing here changes a booking by itself.
*/
class InboundMessageResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = InboundMessage::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedInboxArrowDown;
protected static string|UnitEnum|null $navigationGroup = 'Verwaltung';
protected static ?string $navigationLabel = 'Posteingang';
protected static ?string $modelLabel = 'Nachricht';
protected static ?string $pluralModelLabel = 'Posteingang';
protected static ?int $navigationSort = 7;
public static function canCreate(): bool
{
return false;
}
public static function getNavigationBadge(): ?string
{
$open = InboundMessage::query()->where('status', InboundMessage::NEEDS_REVIEW)->count();
return $open > 0 ? (string) $open : null;
}
public static function getNavigationBadgeColor(): string
{
return 'warning';
}
public static function table(Table $table): Table
{
return $table
->defaultSort('received_at', 'desc')
->emptyStateHeading('Keine Nachrichten')
->emptyStateDescription('Sobald ein Postfach im Modus „Alle Nachrichten“ eingerichtet ist (System › Betrieb), erscheinen Gast-Mails hier.')
->columns([
TextColumn::make('received_at')->label('Eingang')->dateTime('d.m.Y H:i')->sortable(),
TextColumn::make('from_address')->label('Von')->description(fn (InboundMessage $record): ?string => $record->from_name)->searchable(),
TextColumn::make('subject')->label('Betreff')->wrap()->searchable(),
TextColumn::make('status')->label('Stand')->badge()->formatStateUsing(fn (InboundMessage $record): string => $record->statusLabel())
->color(fn (string $state): string => match ($state) {
InboundMessage::NEEDS_REVIEW => 'warning',
InboundMessage::ASSIGNED => 'info',
InboundMessage::PROCESSED, InboundMessage::PORTAL => 'success',
default => 'gray',
}),
TextColumn::make('booking.reference')->label('Vorgang')->url(fn (InboundMessage $record): ?string => $record->booking ? BookingResource::getUrl('view', ['record' => $record->booking]) : null),
IconColumn::make('test_mode')->label('Testbetrieb')->boolean()->trueIcon(Heroicon::OutlinedBeaker)->falseIcon(null)->tooltip('Im Testbetrieb eingegangen'),
])
->filters([
SelectFilter::make('status')->label('Stand')->options([
InboundMessage::NEEDS_REVIEW => 'zu klären', InboundMessage::ASSIGNED => 'zugeordnet', InboundMessage::PROCESSED => 'erledigt',
InboundMessage::PORTAL => 'Portal-Mail', InboundMessage::IGNORED => 'ignoriert',
]),
])
->recordActions([
Action::make('read')->label('Lesen')->icon(Heroicon::OutlinedEye)->button()
->modalHeading(fn (InboundMessage $record): string => (string) $record->subject)
->modalSubmitAction(false)->modalCancelActionLabel('Schließen')->modalWidth('3xl')
->schema([
TextEntry::make('from')->label('Von')->state(fn (InboundMessage $record): string => trim(($record->from_name ? $record->from_name.' · ' : '').$record->from_address)),
TextEntry::make('hints_text')->label('Hinweise')->state(fn (InboundMessage $record): string => collect((array) $record->hints)->map(fn (array $hint): string => $hint['reference'].': '.$hint['why'])->implode(' · ') ?: 'keine')
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW),
TextEntry::make('proposals_text')->label('Erkannte Angaben (KI-Vorschläge)')
->state(fn (InboundMessage $record): HtmlString => new HtmlString(collect((array) ($record->extraction['proposed'] ?? []))
->map(fn (array $fact): string => e(CaseRequirements::label($fact['field']).': „'.$fact['value'].'“').($fact['problems'] !== [] ? ' <em>('.e(implode(', ', $fact['problems'])).')</em>' : ' <em>(unsicher)</em>'))
->implode('<br>') ?: '–'))
->visible(fn (InboundMessage $record): bool => ($record->extraction['proposed'] ?? []) !== []),
TextEntry::make('applied_text')->label('Automatisch übernommen')
->state(fn (InboundMessage $record): string => collect((array) ($record->extraction['applied'] ?? []))->map(fn (array $fact): string => CaseRequirements::label($fact['field']).': „'.$fact['value'].'“')->implode(' · '))
->visible(fn (InboundMessage $record): bool => ($record->extraction['applied'] ?? []) !== []),
TextEntry::make('body_text')->label('Nachricht')->state(fn (InboundMessage $record): HtmlString => new HtmlString(nl2br(e((string) $record->body)))),
]),
Action::make('assign')->label('Vorgang zuordnen')->icon(Heroicon::OutlinedLink)
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW)
->schema([
Select::make('booking_id')->label('Vorgang')->required()->searchable()
->options(fn (InboundMessage $record): array => self::caseOptions($record)),
])
->action(function (InboundMessage $record, array $data, RequestCaseData $requests): void {
$booking = Booking::query()->findOrFail($data['booking_id']);
$record->update(['status' => InboundMessage::ASSIGNED, 'booking_id' => $booking->id, 'match_reason' => 'landlord']);
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.']);
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)
->modalDescription('Es entsteht eine unverbindliche Anfrage wie über die Webseite; der Gast erhält die übliche Eingangsbestätigung bzw. Rückfrage. Termine und Personenzahl bitte aus der Nachricht übernehmen.')
->fillForm(fn (InboundMessage $record): array => [
'property_id' => Property::query()->orderBy('id')->value('id'),
'email' => $record->from_address,
'first_name' => str($record->from_name ?? '')->before(' ')->toString(),
'last_name' => str($record->from_name ?? '')->after(' ')->toString(),
'guests' => 2,
])
->schema([
Select::make('property_id')->label('Wohnung')->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())->required(),
DatePicker::make('arrival')->label('Anreise')->required(),
DatePicker::make('departure')->label('Abreise')->required()->after('arrival'),
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->required(),
TextInput::make('first_name')->label('Vorname')->required(),
TextInput::make('last_name')->label('Nachname')->required(),
TextInput::make('email')->label('E-Mail')->email()->required(),
])
->action(function (InboundMessage $record, array $data, CreateReservation $create): void {
try {
$booking = $create->handle(Property::query()->findOrFail($data['property_id']), new StayRequest(CarbonImmutable::parse($data['arrival']), CarbonImmutable::parse($data['departure']), (int) $data['guests']),
['first_name' => $data['first_name'], 'last_name' => $data['last_name'], 'email' => $data['email']], mb_substr((string) $record->body, 0, 2000), source: 'email');
} catch (QuoteException|ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
}
$record->update(['status' => InboundMessage::PROCESSED, 'booking_id' => $booking->id, 'match_reason' => 'new_request', 'processed_at' => now()]);
Notification::make()->title('Anfrage '.$booking->reference.' angelegt')->success()->send();
}),
Action::make('applyProposals')->label('Vorschläge übernehmen')->icon(Heroicon::OutlinedCheckBadge)
->visible(fn (InboundMessage $record): bool => $record->booking_id !== null && ($record->extraction['proposed'] ?? []) !== [])
->modalDescription('Nur übernehmen, was Sie in der Nachricht selbst geprüft haben. Zeitraum und Personenzahl ändern Sie über „Buchung ändern“ bzw. ein neues Angebot.')
->schema([
CheckboxList::make('fields')->label('Angaben')->required()
->options(fn (InboundMessage $record): array => collect((array) ($record->extraction['proposed'] ?? []))
->reject(fn (array $fact): bool => in_array($fact['field'], ContributeCaseFacts::STAY_FIELDS, true))
->mapWithKeys(fn (array $fact): array => [$fact['field'] => CaseRequirements::label($fact['field']).': „'.$fact['value'].'“'])->all()),
])
->action(function (InboundMessage $record, array $data, ContributeCaseFacts $facts): void {
$chosen = collect((array) ($record->extraction['proposed'] ?? []))->whereIn('field', $data['fields']);
$result = $facts->handle($record->booking, $chosen->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['value']])->all(), FactSource::Landlord, [
'inbound_message_id' => $record->id,
'reference' => 'message-landlord:'.$record->id,
'evidence' => $chosen->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['evidence']])->all(),
]);
$record->update(['extraction' => [...(array) $record->extraction, 'proposed' => collect((array) ($record->extraction['proposed'] ?? []))->whereNotIn('field', $data['fields'])->values()->all()]]);
Notification::make()->title('Übernommen')->body($result->summary())->success()->send();
}),
ActionGroup::make([
Action::make('done')->label('Als erledigt markieren')->icon(Heroicon::OutlinedCheck)
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::ASSIGNED)
->action(function (InboundMessage $record): void {
$record->update(['status' => InboundMessage::PROCESSED, 'processed_at' => now()]);
BookingTask::query()->where('booking_id', $record->booking_id)->where('kind', BookingTaskKind::InboundReview)->where('subject', 'm'.$record->id)->where('status', BookingTaskStatus::Open)
->get()->each(fn (BookingTask $task): bool => $task->forceFill(['status' => BookingTaskStatus::Done, 'completed_at' => now(), 'completed_by' => auth()->user()?->name])->save());
}),
Action::make('ignore')->label('Ignorieren')->icon(Heroicon::OutlinedEyeSlash)->color('gray')
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW)
->action(fn (InboundMessage $record) => $record->update(['status' => InboundMessage::IGNORED, 'processed_at' => now()])),
]),
]);
}
/**
* 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.
*
* @return array<int, string>
*/
public static function caseOptions(InboundMessage $message): array
{
$hinted = collect((array) $message->hints)->pluck('booking_id')->all();
return Booking::query()->with('guest')
->where(fn (Builder $query) => $query->whereKey($hinted)->orWhereNotIn('status', [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed]))
->orderByRaw('CASE WHEN id IN ('.(implode(',', array_map('intval', $hinted)) ?: '0').') THEN 0 ELSE 1 END')->orderBy('arrival')
->limit(100)->get()
->mapWithKeys(fn (Booking $booking): array => [$booking->id => $booking->reference.' · '.$booking->guestName().' · '.$booking->arrival->format('d.m.').'–'.$booking->departure->format('d.m.Y')])
->all();
}
public static function getPages(): array
{
return ['index' => ListInboundMessages::route('/')];
}
}