Files
fewo-stommer/app/Actions/ExtractMessageFacts.php
T
LarsandClaude Opus 5.5 4170e3bd29 v0.11 U6: risikobasierte KI-Extraktion von Gast- und Portalnachrichten
- Kleines Modell (claude-haiku-5-5) extrahiert Fakten mit Belegstelle und
  Konfidenz; programmatische Prüfung (Gültigkeit, Belegstelle im Original,
  Widerspruch zum gespeicherten Wert oder in der Nachricht, Plausibilität,
  Kritikalität nach Feld und Phase). Widerspruch oder fehlgeschlagene
  Prüfung → Prüfmodell (claude-opus-5-5, serverseitiger Fallback bei
  Ablehnung) unabhängig von der Konfidenz; solche Fakten nie automatisch.
- Nur geprüfte, bisher fehlende Angaben gehen an den Fakteneingang (Quelle
  „llm“); Zeitraum/Personen nur als Änderungswunsch (M06); Rest als
  Vorschlag im Posteingang („Vorschläge übernehmen“).
- Versionierte Prompts mit Platzhaltern, JSON-Schema mit eigener
  Validierung und einer Wiederholung; Ausfall/Ablehnung → sicherer
  Rückfall zur Vermieterin. HTTP-Client, kein SDK (laut Plan).
- Dienst „KI: Gästekommunikation“ verdrahtet, standardmäßig aus;
  Schlüssel je Mandant oder FEWO_AI_API_KEY; Verbrauch in service_usages.
- messages:extract alle fünf Minuten; ai:evaluate misst Fehlwerte und
  übersehene Angaben getrennt (M05).

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

189 lines
9.6 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\Actions;
use App\Communication\Extraction\ExtractionFailed;
use App\Communication\Extraction\MessageExtractor;
use App\Communication\Extraction\RiskAssessment;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\FactSource;
use App\Enums\TenantServiceKey;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\InboundMessage;
use App\Models\ServiceUsage;
use App\Models\TenantService;
use App\Process\CaseLog;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
/**
* The risk-based two-stage extraction of v0.11 (CH-14, E-035): the small model extracts facts with evidence and
* confidence, programmatic rules check phase, stored values, contradictions and plausibility, and – when the risk is
* high, something contradicts or a check fails – the review model looks at the original and the first extraction.
* Only facts that pass every check go to the common fact intake (which applies its own rules); everything else is
* proposed to the landlord in the inbox. Wishes to change the stay only become change requests. The extraction
* decides nothing binding; without the service, a key or a usable answer the message simply waits for the landlord.
*/
class ExtractMessageFacts
{
public function __construct(private MessageExtractor $extractor, private RiskAssessment $risk, private ContributeCaseFacts $facts) {}
/**
* @return string the extraction status: done, failed or disabled
*/
public function handle(InboundMessage $message): string
{
$booking = $message->booking()->with(['guest', 'property'])->first();
if ($booking === null || $message->extraction_status !== null) {
return (string) $message->extraction_status;
}
$apiKey = $this->apiKey();
if (! app(TenantFeatures::class)->enabled(TenantServiceKey::AiGuestMail) || $apiKey === null) {
$message->update(['extraction_status' => 'disabled']);
return 'disabled';
}
$record = ['prompt_version' => MessageExtractor::promptVersion()];
try {
$first = $this->extractor->extract($apiKey, $message, $booking);
$this->meter();
$record['first'] = $first;
$data = $first['data'];
$checked = $this->risk->facts($booking, (string) $message->body, $data);
if ($this->risk->needsReview($booking, $checked, $data)) {
$review = $this->extractor->review($apiKey, $message, $booking, $data);
$this->meter();
$record['review'] = $review;
$data = $review['data'];
$checked = $this->markDisagreements($this->risk->facts($booking, (string) $message->body, $data), $first['data']);
}
} catch (ExtractionFailed $exception) {
$message->update(['extraction_status' => 'failed', 'extraction' => [...$record, 'error' => $exception->getMessage()]]);
CaseLog::record($booking, 'mail_in', 'Automatische Auswertung nicht möglich – bitte die Nachricht selbst lesen', actor: CaseLog::SYSTEM);
return 'failed';
}
$automatic = array_values(array_filter($checked, fn (array $fact): bool => $this->risk->mayTakeOver($booking, $fact)));
$proposed = array_values(array_filter($checked, fn (array $fact): bool => ! in_array($fact, $automatic, true)));
$source = $message->status === InboundMessage::PORTAL ? FactSource::PortalMail : FactSource::Extraction;
if ($automatic !== []) {
$this->facts->handle($booking, collect($automatic)->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['value']])->all(), $source, [
'inbound_message_id' => $message->id,
'reference' => 'message:'.$message->id,
'evidence' => collect($automatic)->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['evidence']])->all(),
'confidence' => collect($automatic)->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['confidence']])->all(),
'actor' => 'Auswertung der E-Mail (KI, geprüft nach Regeln)',
]);
}
$changes = $this->changeRequests($booking, $message, $data['change_requests']);
$message->update([
'extraction_status' => 'done',
'extraction' => [...$record, 'intent' => $data['intent'], 'uncertainties' => $data['uncertainties'], 'applied' => $automatic, 'proposed' => $proposed, 'change_requests' => $changes],
]);
$this->finish($message, $automatic, $proposed, $changes, $data['intent']);
return 'done';
}
/**
* Facts the two models disagree on are proposed, never taken over.
*
* @param list<array<string, mixed>> $checked
* @param array{facts: list<array{field: string, value: string}>} $first
* @return list<array<string, mixed>>
*/
private function markDisagreements(array $checked, array $first): array
{
$firstValues = collect($first['facts'])->mapWithKeys(fn (array $fact): array => [$fact['field'] => mb_strtolower(trim($fact['value']))])->all();
return array_map(function (array $fact) use ($firstValues): array {
if (isset($firstValues[$fact['field']]) && $firstValues[$fact['field']] !== mb_strtolower($fact['value'])) {
$fact['problems'][] = 'die beiden Modelle lesen den Wert unterschiedlich';
}
return $fact;
}, $checked);
}
/**
* Wishes to change the stay become change requests through the fact intake (dates, guests) or a task; nothing about
* the booking changes (E-038).
*
* @param list<array{field: string, value: string, evidence: string}> $requests
* @return list<array{field: string, value: string, evidence: string}>
*/
private function changeRequests(Booking $booking, InboundMessage $message, array $requests): array
{
$kept = array_values(array_filter($requests, fn (array $request): bool => $this->risk->evidenceFound((string) $message->body, $request['evidence'])));
$stay = array_filter($kept, fn (array $request): bool => in_array($request['field'], ContributeCaseFacts::STAY_FIELDS, true));
if ($stay !== []) {
$this->facts->handle($booking, collect($stay)->mapWithKeys(fn (array $request): array => [$request['field'] => $request['value']])->all(), FactSource::Extraction, [
'inbound_message_id' => $message->id, 'reference' => 'message-change:'.$message->id, 'advance' => false,
'evidence' => collect($stay)->mapWithKeys(fn (array $request): array => [$request['field'] => $request['evidence']])->all(),
]);
}
foreach (array_filter($kept, fn (array $request): bool => ! in_array($request['field'], ContributeCaseFacts::STAY_FIELDS, true)) as $request) {
BookingTask::openOnce($booking, BookingTaskKind::ChangeRequest, 'message:'.$message->id.':'.$request['field'], [
'due_on' => today(),
'note' => 'Wunsch laut E-Mail ('.$request['field'].'): „'.mb_substr($request['evidence'], 0, 200).'“. Nichts wurde geändert.',
]);
}
return $kept;
}
/**
* @param list<array<string, mixed>> $automatic
* @param list<array<string, mixed>> $proposed
* @param list<array<string, mixed>> $changes
*/
private function finish(InboundMessage $message, array $automatic, array $proposed, array $changes, string $intent): void
{
$booking = $message->booking;
$task = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::InboundReview)->where('subject', 'm'.$message->id)->where('status', BookingTaskStatus::Open)->first();
$parts = array_filter([
$automatic !== [] ? count($automatic).' Angabe(n) übernommen' : null,
$proposed !== [] ? count($proposed).' Vorschlag/Vorschläge zu prüfen' : null,
$changes !== [] ? 'Änderungswunsch erkannt' : null,
]);
CaseLog::record($booking, 'mail_in', 'E-Mail ausgewertet: '.($parts === [] ? 'keine Angaben erkannt' : implode(', ', $parts)), actor: CaseLog::SYSTEM);
// Nothing left to look at: a pure answer whose details were all taken over.
if ($proposed === [] && $changes === [] && $automatic !== [] && $intent === 'answer') {
$task?->forceFill(['status' => BookingTaskStatus::Done, 'completed_at' => now(), 'completed_by' => CaseLog::SYSTEM, 'note' => trim($task->note.' · automatisch ausgewertet')])->save();
$message->update(['status' => $message->status === InboundMessage::PORTAL ? InboundMessage::PORTAL : InboundMessage::PROCESSED, 'processed_at' => now()]);
return;
}
$task?->forceFill(['note' => '„'.mb_substr((string) $message->subject, 0, 120).'“ – '.(implode(', ', $parts) ?: 'keine Angaben erkannt').'. Im Posteingang ansehen.'])->save();
}
/**
* The landlord's own key of the service, otherwise the operator's key of the installation.
*/
private function apiKey(): ?string
{
$tenant = Settings::tenant();
$own = $tenant === null ? null : TenantService::query()->where('tenant_id', $tenant->id)->where('service', TenantServiceKey::AiGuestMail->value)->first()?->api_key;
return filled($own) ? (string) $own : (filled(config('fewo.ai.api_key')) ? (string) config('fewo.ai.api_key') : null);
}
private function meter(): void
{
if (($tenant = Settings::tenant()) !== null) {
ServiceUsage::query()->create(['tenant_id' => $tenant->id, 'service' => TenantServiceKey::AiGuestMail->value, 'quantity' => 1, 'used_at' => now()]);
}
}
}