presseportale/app/Services/SearchConsole/IndexStatusReport.php
Kevin Adametz c26bdff681 admin: Bericht „Indexierung & Abrufe" — Rolle Erstquelle/Kopie, Quellenbefund, Crawler-Abrufe; Schlüsselpfad ab Projektwurzel
Der Bericht meldete auf Live „nicht konfiguriert", während der Lauf
längst Daten holte: der relative Pfad der Schlüsseldatei war im Cron
(Projektwurzel) lesbar, im Web-Request (public/) nicht. Relative Pfade
werden jetzt ab base_path() aufgelöst.

Die Verteilung trennt zusätzlich nach Rolle in der kanonischen Zuordnung
(1c.8): bei einer Kopie mit Verweis ist „ausgeschlossen" der erwartete
Befund. Neu: Quellenbefund über Erstquellen (welche Adresse Google führt,
fremde Hosts), Abrufe durch Such- und KI-Dienste je Dienst, Tag und
Meldung mit CSV. Herkunftsmarker als Join statt korreliertem EXISTS,
Aggregate 15 Minuten gecacht.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 12:53:22 +00:00

228 lines
9.4 KiB
PHP

<?php
namespace App\Services\SearchConsole;
use App\Enums\IndexState;
use App\Enums\Portal;
use App\Models\PressRelease;
use App\Models\PressReleaseIndexCheck;
use App\Scopes\PortalScope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
/**
* Admin-Auswertung des Indexierungsstatus (Roadmap 1c.4/1c.5): Verteilung
* der jüngsten Befunde je Portal, getrennt nach Direkteinreichung und
* Syndikation über die API. Erst diese Verteilung entscheidet, ob und wie
* der Status in die Kundenansicht kommt (E8).
*/
class IndexStatusReport
{
/**
* Ausdruck, der eine Meldung der Herkunft „api" oder „direct" zuordnet:
* Marker ist ein Status-Log-Eintrag mit Quelle „api" (wie beim
* Mail-Versand — der Kontotyp ist nicht verlässlich). Erwartet den
* Join aus apiJoin(): als Join ein Bruchteil der Laufzeit eines
* korrelierten EXISTS über den Bestand (0,3 s statt 2,6 s).
*/
private const string ORIGIN_SQL = "case when api_origin.press_release_id is null then 'direct' else 'api' end";
private const int CACHE_SECONDS = 900;
/**
* Rolle einer Meldung in der kanonischen Zuordnung (1c.8): Erstquelle
* oder Kopie mit rel=canonical auf die andere Fassung. Für eine Kopie ist
* „ausgeschlossen" (Google folgt dem Verweis) der erwartete Befund.
*/
private const string ROLE_SQL = "case when press_releases.canonical_press_release_id is null then 'source' else 'copy' end";
/** @var list<string> */
public const array ORIGINS = ['direct', 'api'];
/** @var list<string> */
public const array ROLES = ['source', 'copy'];
/**
* Anzahl der Meldungen je Portal, Herkunft, Rolle und Befund — Stand der
* jeweils jüngsten Prüfung. Meldungen ohne Prüfung erscheinen unter
* `unchecked`.
*
* @return array<string, array<string, array<string, array<string, int>>>> portal => origin => role => state|unchecked|total => count
*/
public function distribution(): array
{
return Cache::remember('index-status.distribution', self::CACHE_SECONDS, fn (): array => $this->computeDistribution());
}
/**
* @return array<string, array<string, array<string, array<string, int>>>>
*/
private function computeDistribution(): array
{
$rows = [];
foreach ([Portal::Presseecho, Portal::Businessportal24] as $portal) {
// Herkunft und Rolle je Meldung erst in einer abgeleiteten Tabelle
// bestimmen, dann darüber gruppieren — MySQL (only_full_group_by)
// lehnt den korrelierten Ausdruck direkt im GROUP BY ab.
$visible = DB::query()
->fromSub(
$this->apiJoin(PressRelease::query()
->withoutGlobalScope(PortalScope::class)
->visibleInArchive()
->forPortalValues([$portal->value, Portal::Both->value]))
->selectRaw('press_releases.id, '.self::ORIGIN_SQL.' as origin, '.self::ROLE_SQL.' as role'),
'r'
)
->selectRaw('origin, role, count(*) as total')
->groupBy('origin', 'role')
->get();
$checked = DB::query()
->fromSub(
$this->apiJoin($this->latestChecks($portal)
->join('press_releases', 'press_releases.id', '=', 'press_release_index_checks.press_release_id')
->whereNull('press_releases.deleted_at'))
->selectRaw('press_release_index_checks.id, press_release_index_checks.state, '.self::ORIGIN_SQL.' as origin, '.self::ROLE_SQL.' as role'),
'c'
)
->selectRaw('origin, role, state, count(*) as total')
->groupBy('origin', 'role', 'state')
->get();
foreach (self::ORIGINS as $origin) {
foreach (self::ROLES as $role) {
$bucket = ['total' => 0, 'unchecked' => 0];
foreach (IndexState::cases() as $state) {
$bucket[$state->value] = 0;
}
$bucket['total'] = (int) ($visible->first(fn (object $row): bool => $row->origin === $origin && $row->role === $role)->total ?? 0);
$checkedTotal = 0;
foreach ($checked->filter(fn (object $row): bool => $row->origin === $origin && $row->role === $role) as $row) {
$bucket[(string) $row->state] = (int) $row->total;
$checkedTotal += (int) $row->total;
}
$bucket['unchecked'] = max(0, $bucket['total'] - $checkedTotal);
$rows[$portal->value][$origin][$role] = $bucket;
}
}
}
return $rows;
}
/**
* Quellenbefund (1c.9) über die jüngsten Prüfungen je Portal: welche
* Adresse Google als maßgeblich führt — diese, die eigene Fassung auf dem
* anderen Portal, ein fremdes Portal, oder keine Angabe. Nur Erstquellen
* (1c.8) zählen: bei einer Kopie ist die Abweichung gewollt.
*
* @return array<string, array{self: int, own_other: int, foreign: int, unknown: int, total: int, foreign_hosts: array<string, int>}>
*/
public function sourceSummary(IndexStatusChecker $checker): array
{
return Cache::remember('index-status.sources', self::CACHE_SECONDS, fn (): array => $this->computeSourceSummary($checker));
}
/**
* @return array<string, array{self: int, own_other: int, foreign: int, unknown: int, total: int, foreign_hosts: array<string, int>}>
*/
private function computeSourceSummary(IndexStatusChecker $checker): array
{
$summary = [];
foreach ([Portal::Presseecho, Portal::Businessportal24] as $portal) {
$bucket = ['self' => 0, 'own_other' => 0, 'foreign' => 0, 'unknown' => 0, 'total' => 0, 'foreign_hosts' => []];
$this->latestChecks($portal)
->join('press_releases', 'press_releases.id', '=', 'press_release_index_checks.press_release_id')
->whereNull('press_releases.deleted_at')
->whereNull('press_releases.canonical_press_release_id')
->select(['press_release_index_checks.id', 'press_release_index_checks.url', 'press_release_index_checks.google_canonical', 'press_release_index_checks.portal'])
->lazyById(1000, 'press_release_index_checks.id', 'id')
->each(function (PressReleaseIndexCheck $check) use (&$bucket, $checker): void {
$verdict = $checker->sourceVerdict($check);
$bucket[$verdict['kind']]++;
$bucket['total']++;
if ($verdict['kind'] === 'foreign' && $verdict['host'] !== null) {
$bucket['foreign_hosts'][$verdict['host']] = ($bucket['foreign_hosts'][$verdict['host']] ?? 0) + 1;
}
});
arsort($bucket['foreign_hosts']);
$bucket['foreign_hosts'] = array_slice($bucket['foreign_hosts'], 0, 10, true);
$summary[$portal->value] = $bucket;
}
return $summary;
}
/**
* Jüngste Prüfungen, neueste zuerst.
*
* @return Collection<int, PressReleaseIndexCheck>
*/
public function latest(int $limit = 100): Collection
{
return PressReleaseIndexCheck::query()
->with(['pressRelease' => fn ($query) => $query->withoutGlobalScopes()->select(['id', 'title', 'slug', 'published_at', 'canonical_press_release_id'])])
->orderByDesc('checked_at')
->orderByDesc('id')
->limit($limit)
->get();
}
public function lastCheckedAt(): ?Carbon
{
$value = PressReleaseIndexCheck::query()->max('checked_at');
return $value ? Carbon::parse((string) $value) : null;
}
/**
* Herkunftsmarker als Join: alle Meldungen, die je einen Status-Log-
* Eintrag mit Quelle „api" haben.
*
* @template TModel of \Illuminate\Database\Eloquent\Model
*
* @param Builder<TModel> $query
* @return Builder<TModel>
*/
private function apiJoin(Builder $query): Builder
{
$api = DB::table('press_release_status_logs')
->select('press_release_id')
->where('source', 'api')
->distinct();
return $query->leftJoinSub($api, 'api_origin', 'api_origin.press_release_id', '=', 'press_releases.id');
}
/**
* Jeweils jüngste Prüfung je Meldung auf einem Portal.
*
* @return Builder<PressReleaseIndexCheck>
*/
private function latestChecks(Portal $portal): Builder
{
$latest = PressReleaseIndexCheck::query()
->select('press_release_id', DB::raw('max(checked_at) as last_checked_at'))
->where('portal', $portal->value)
->groupBy('press_release_id');
return PressReleaseIndexCheck::query()
->joinSub($latest, 'latest', fn ($join) => $join
->on('latest.press_release_id', '=', 'press_release_index_checks.press_release_id')
->on('latest.last_checked_at', '=', 'press_release_index_checks.checked_at'))
->where('press_release_index_checks.portal', $portal->value);
}
}