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'] !== [] ? ' ('.e(implode(', ', $fact['problems'])).')' : ' (unsicher)'))
->implode('
') ?: '–'))
->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
*/
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('/')];
}
}