presseportale/app/Services/Customer/CustomerCompanyContext.php
Kevin Adametz f235156de9 web/api/ki: Soft Deletes wieder wirksam, Caches bei Firmenwechsel, KI-Ergebnis an Inhalt gebunden (Audit Block 3+4, Deploy D)
Block 3 — Sichtbarkeit, Löschung, Cache, Eingaben

F04: withoutGlobalScopes() ohne Argument entfernte neben dem PortalScope
auch den Soft-Delete-Filter. Öffentliche, Kunden-, API-, Vorschau- und
Medienpfade sowie die PressRelease-Helfer schreiben jetzt
withoutGlobalScope(PortalScope::class). Zwei Stellen, die der Audit nicht
kannte: die öffentliche Meldungsseite zeigte gelöschte Firmenkontakte mit
Name, Mail und Telefon; das Pressefach listete gelöschte Kontakte weiter
und ließ sie bearbeiten. Ein Architekturtest friert die 39 bewusst
verbliebenen Stellen (Admin, Importer, Befehle, Slug-Eindeutigkeit) ein.
Der Vorschau-Test prüfte bisher forceDelete statt delete.

F22: LOWER(email) machte auf companies (110k Zeilen) bei jedem Login einen
Vollscan; die Kollation ist ohnehin case-insensitiv. EmailQuery vergleicht
auf MySQL direkt über den Index, auf SQLite (Tests) weiter per LOWER.
Neuer Index contacts_email_idx.

F13: Firmen-Observer verwirft die öffentlichen Seiten-Caches bei
Löschung, Wiederherstellung und is_active-Wechsel auf jedem Weg; die
Newsroom-Seite prüft Sichtbarkeit vor dem Cache-Treffer; Kontakt-
Änderungen im Pressefach flushen. Der Tombstone-Test wärmte den Cache
vorher nicht und traf den Fehler nie.

F12: Gemeldete URLs werden über Host, Ausgabe und Slug aufgelöst
(ReportedUrlResolver); fremde Hosts zählen nicht, bei Doppelveröffentlichung
gewinnt die Erstquelle.

F11: per_page 1–100, status als Enum, language nur de/en, Kategorie muss
aktiv sein und zum Ziel-Portal passen. Legacy-Aliasse behalten ihren
Vertrag.

F23: Rückgabewert von put() wird geprüft; Logo erst speichern, dann
Datenbank, dann altes Logo löschen. Fehler enden als Feldfehler, nicht
als verlorenes Logo.

Block 4 — KI-Prüfung und Scheduler

F07: Klassifikation und Score tragen die Prüfsumme des Inhalts bei
Einplanung. Weicht sie beim Speichern ab, wird das Ergebnis verworfen
(ki_audits.discarded_at) und ein neuer Lauf eingeplant. Der Scheduler
veröffentlicht keine Meldung, deren jüngste Klassifikation nicht zum
aktuellen Text passt, sondern plant eine Prüfung mit Routing ein.

F18: Kontingent an den Kalendermonat gebunden (users.press_release_quota_period).
Verbrauch aus einem früheren Monat zählt null, auch ohne Reset-Cron; der
Reset ist idempotent und lässt den laufenden Monat in Ruhe.

F20: Der Publikations-Scheduler liefert bei technischen Fehlern einen
Fehler-Exit-Code, damit der Failure-Hook greift.

F17: KI-Jobs mit $timeout = 120, retry_after 150; Runbook ergänzt.

F19: Aggregation der Aufrufe unter einem Cache-Lock für alle Einstiege.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 10:40:48 +00:00

257 lines
7.5 KiB
PHP

<?php
namespace App\Services\Customer;
use App\Enums\Portal;
use App\Models\Company;
use App\Models\User;
use App\Scopes\PortalScope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
class CustomerCompanyContext
{
public const SessionKey = 'customer_company_context_id';
/**
* @return Collection<int, Company>
*/
public function companiesFor(User $user): Collection
{
$linkedCompanies = $user->companies()
->withoutGlobalScope(PortalScope::class)
->select(['companies.id', 'companies.name', 'companies.portal', 'companies.owner_user_id'])
->withPivot('role')
->get();
$ownedCompanies = $user->ownedCompanies()
->withoutGlobalScope(PortalScope::class)
->whereNotIn('id', $linkedCompanies->pluck('id'))
->get(['id', 'name', 'portal', 'owner_user_id']);
return $linkedCompanies
->concat($ownedCompanies)
->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)
->values();
}
public function selectedCompanyId(User $user): ?int
{
$companyId = session(self::SessionKey);
if (! is_numeric($companyId)) {
return null;
}
$companyId = (int) $companyId;
if (! $this->userCanAccessCompany($user, $companyId)) {
$this->clear();
return null;
}
return $companyId;
}
public function selectedCompany(User $user): ?Company
{
$companyId = session(self::SessionKey);
if (! is_numeric($companyId)) {
return null;
}
// Eine einzige Abfrage statt exists()+first(): findFor prüft den Zugriff
// bereits über accessibleBy. Ist die Firma nicht (mehr) erreichbar, wird
// die Auswahl wie in selectedCompanyId verworfen.
$company = $this->findFor($user, (int) $companyId);
if ($company === null) {
$this->clear();
}
return $company;
}
/**
* @return Collection<int, Company>
*/
public function latestCompaniesFor(User $user, int $limit = 10): Collection
{
return $this->accessibleCompanyQuery($user)
->select(['companies.id', 'companies.name', 'companies.portal', 'companies.owner_user_id', 'companies.created_at'])
->latest('companies.created_at')
->latest('companies.id')
->limit($limit)
->get();
}
/**
* @return Collection<int, Company>
*/
public function searchCompaniesFor(User $user, string $term = '', ?int $selectedCompanyId = null, int $limit = 10): Collection
{
$term = Portal::stripTrailingAbbreviation($term);
$limit = max(1, $limit);
if ($term === '') {
return $this->companyOptionsWithSelected($user, $selectedCompanyId, $limit);
}
return $this->companyOptionQuery($user)
->where(function (Builder $query) use ($term): void {
$query->where('companies.name', 'like', '%'.$term.'%')
->orWhere('companies.slug', 'like', '%'.$term.'%')
->orWhere('companies.email', 'like', '%'.$term.'%');
})
->orderBy('companies.name')
->orderBy('companies.id')
->limit($limit)
->get();
}
public function companyCountFor(User $user): int
{
return $this->accessibleCompanyQuery($user)->count();
}
/**
* @return Collection<int, Company>
*/
public function switcherCompaniesFor(User $user, ?int $selectedCompanyId = null, int $limit = 50): Collection
{
$companies = $this->switcherCompanyQuery($user)
->latest('companies.created_at')
->latest('companies.id')
->limit($limit)
->get();
if ($selectedCompanyId === null || $companies->contains('id', $selectedCompanyId)) {
return $companies;
}
$selectedCompany = $this->switcherCompanyQuery($user)
->whereKey($selectedCompanyId)
->first();
if (! $selectedCompany) {
return $companies;
}
return $companies
->prepend($selectedCompany)
->unique('id')
->values();
}
/**
* @return Builder<Company>
*/
public function accessibleCompanyQuery(User $user): Builder
{
return Company::query()
->withoutGlobalScope(PortalScope::class)
->accessibleBy($user);
}
public function findFor(User $user, int $companyId): ?Company
{
return $this->accessibleCompanyQuery($user)
->whereKey($companyId)
->first();
}
public function select(User $user, ?int $companyId): void
{
if ($companyId === null) {
$this->clear();
return;
}
if (! $this->userCanAccessCompany($user, $companyId)) {
return;
}
session([self::SessionKey => $companyId]);
}
public function clear(): void
{
Session::forget(self::SessionKey);
}
public function roleLabelFor(Company $company, User $user): string
{
$role = $company->owner_user_id === $user->id
? 'owner'
: ($company->getAttribute('current_user_role') ?? $company->pivot?->role ?? 'member');
return match ($role) {
'owner' => __('Owner'),
'responsible' => __('Verantwortlich'),
default => __('Mitglied'),
};
}
/**
* @return Builder<Company>
*/
private function switcherCompanyQuery(User $user): Builder
{
return $this->accessibleCompanyQuery($user)
->select(['companies.id', 'companies.name', 'companies.portal', 'companies.owner_user_id', 'companies.created_at'])
->addSelect([
'current_user_role' => DB::table('company_user')
->select('role')
->whereColumn('company_user.company_id', 'companies.id')
->where('company_user.user_id', $user->id)
->limit(1),
]);
}
/**
* @return Builder<Company>
*/
private function companyOptionQuery(User $user): Builder
{
return $this->accessibleCompanyQuery($user)
->select(['companies.id', 'companies.name', 'companies.portal', 'companies.owner_user_id', 'companies.created_at']);
}
/**
* @return Collection<int, Company>
*/
private function companyOptionsWithSelected(User $user, ?int $selectedCompanyId, int $limit): Collection
{
$selectedCompany = $selectedCompanyId
? $this->companyOptionQuery($user)->whereKey($selectedCompanyId)->first()
: null;
$companies = $this->companyOptionQuery($user)
->when($selectedCompany, fn (Builder $query): Builder => $query->whereKeyNot($selectedCompany->id))
->latest('companies.created_at')
->latest('companies.id')
->limit($selectedCompany ? max(0, $limit - 1) : $limit)
->get();
if (! $selectedCompany) {
return $companies;
}
return $companies
->prepend($selectedCompany)
->unique('id')
->values();
}
private function userCanAccessCompany(User $user, int $companyId): bool
{
return $this->accessibleCompanyQuery($user)
->whereKey($companyId)
->exists();
}
}