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> $checked * @param array{facts: list} $first * @return list> */ 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 $requests * @return list */ 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> $automatic * @param list> $proposed * @param list> $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()]); } } }