Files
fewo-stommer/app/Filament/Resources/InboundMessages/InboundMessageResource.php
T
LarsandClaude Opus 5.5 dff9e2344e v0.11 U5: Posteingang, deterministische Zuordnung, Klärungsansicht
- mailboxes (Modell für mehrere, eines aktiv): Übernahme des bisherigen
  Postfachs als „nur Portal-Mails“; Modus „alle Nachrichten“ für ein
  eigenes Postfach; Adresse als Antwortadresse der Rückfragen.
- inbound_messages: jede Nachricht zuerst gespeichert, einmal je
  Message-ID, mit Testbetriebs-Kennzeichen (M10). Portal-Mails laufen
  unverändert über den Portalpfad (CH-08).
- MessageMatcher (CH-13, ohne Scoring): Antwortbezug; Vorgangsnummer nur
  mit dem Gast als Absender; sonst Absender + Wohnung + beide Termine eines
  einzigen offenen Vorgangs. Ein offener Vorgang des Absenders allein
  genügt nicht (nur Hinweis). Alles andere → Klärung (M04).
- Ausgehende Mails speichern ihre Message-ID; Antwort stoppt Erinnerungen.
- Filament „Posteingang“: lesen, Vorgang zuordnen, als neue Anfrage
  anlegen, ignorieren, erledigt.

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

198 lines
12 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\CreateReservation;
use App\Actions\RequestCaseData;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
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 BackedEnum;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
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('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.']);
Notification::make()->title('Zugeordnet')->success()->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();
}),
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()])),
]),
]);
}
/**
* 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('/')];
}
}