Deploy FeWo mit PipelineManager / deploy (push) Successful in 5m11s
- Jeder Mandant verbindet unter „System › KI-Anbindung“ seinen eigenen Zugang: Anbieter (Anthropic oder OpenRouter), API-Schlüssel, Modell für die erste Auswertung und für die Prüfung – keine Modellkennung im Code, kein zentraler Betreiberschlüssel (FEWO_AI_API_KEY entfällt). - Gespeichert im bestehenden TenantService (ai_guest_mail): Schlüssel verschlüsselt, nie wieder angezeigt, nie in Meldungen; Anbieter/Modelle in settings, Prüfergebnis in check_status/check_message/checked_at. - Feste Endpunkte je Anbieter (AiProvider), nicht konfigurierbar. OpenRouter mit response_format json_schema (strict) und provider.require_parameters. - „Verbindung prüfen“ testet beide Modelle. Ein abgelehnter Zugang (401/402/403) schaltet die Auswertung für den Mandanten ab, meldet es im Postfach der Verwaltung; Nachrichten bleiben zur Prüfung im Posteingang. - Zweistufige Extraktion und ihre Sicherheitsregeln unverändert. - Zielarchitektur §3.8, Umsetzungsplan U6, Bericht, Drehbuch, Status. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
189 lines
10 KiB
PHP
189 lines
10 KiB
PHP
<?php
|
||
|
||
namespace App\Actions;
|
||
|
||
use App\Communication\Extraction\AccessRejected;
|
||
use App\Communication\Extraction\AiAccess;
|
||
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\InboxMessageKind;
|
||
use App\Enums\TenantServiceKey;
|
||
use App\Filament\Pages\AiConnection;
|
||
use App\Models\Booking;
|
||
use App\Models\BookingTask;
|
||
use App\Models\InboundMessage;
|
||
use App\Models\ServiceUsage;
|
||
use App\Process\CaseLog;
|
||
use App\Support\Inbox;
|
||
use App\Support\Settings;
|
||
|
||
/**
|
||
* 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;
|
||
}
|
||
|
||
// Bring your own key: only the landlord's own, complete and not rejected access is used.
|
||
$access = AiAccess::for(Settings::tenant());
|
||
if ($access === null) {
|
||
$message->update(['extraction_status' => 'disabled']);
|
||
|
||
return 'disabled';
|
||
}
|
||
|
||
$record = ['prompt_version' => MessageExtractor::promptVersion()];
|
||
try {
|
||
$first = $this->extractor->extract($access, $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($access, $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 (AccessRejected $exception) {
|
||
// The access is no longer valid: off for this landlord until he saves or checks it again (no retry loop).
|
||
AiAccess::markInvalid(Settings::tenant(), $exception->getMessage());
|
||
app(Inbox::class)->post(InboxMessageKind::AiAccessRejected, 'ai-access', 'KI-Anbindung abgelehnt', $exception->getMessage().' Die automatische Auswertung ist ausgeschaltet, bis Sie den Zugang unter System › KI-Anbindung prüfen. Nachrichten liegen im Posteingang.', actionUrl: AiConnection::getUrl());
|
||
$message->update(['extraction_status' => 'failed', 'extraction' => [...$record, 'error' => $exception->getMessage()]]);
|
||
|
||
return 'failed';
|
||
} 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();
|
||
}
|
||
|
||
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()]);
|
||
}
|
||
}
|
||
}
|