presseportale/app/Models/PressRelease.php
Kevin Adametz 1ff1cc3626 WS-8: N+1 entschaerfen und PM-Zugriffsmuster konsolidieren
- User::currentPlan() und hasUnlimitedPressReleaseQuota() pro Request
  memoisiert. Beide werden je Render mehrfach abgefragt (Status-Widget auf
  jeder Seite, Buchungsseite, Quota-Methoden) und loesten bisher jeweils
  eigene subscription-/Plan-/payment-option-Queries aus. fresh() setzt den
  Cache zurueck.
- show.blade.php: getMyPR() war NICHT memoisiert und wurde pro Request bis
  zu 7x mit voller Eager-Load-Query aufgerufen -> jetzt memoisiert. Firmen-
  Kennzahlen direkt per withCount() eager geladen statt nachtraeglichem
  loadCount().
- Dupliziertes Zugriffsmuster (withoutGlobalScopes + user_id/company_id) aus
  edit/show/index in PressRelease::scopeAccessibleBy(User) zentralisiert
  (Single Source of Truth fuer Kunden-PM-Zugriff), mit Tests abgesichert.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:27:39 +00:00

222 lines
6.2 KiB
PHP

<?php
namespace App\Models;
use App\Enums\Portal;
use App\Enums\PressReleaseClassification;
use App\Enums\PressReleaseContentTier;
use App\Enums\PressReleasePlaceholder;
use App\Enums\PressReleaseStatus;
use App\Models\Concerns\HasUniqueSlug;
use App\Scopes\PortalScope;
use App\Services\PressRelease\PressReleaseHtmlSanitizer;
use Database\Factories\PressReleaseFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
use Illuminate\Support\HtmlString;
class PressRelease extends Model
{
/** @use HasFactory<PressReleaseFactory> */
use HasFactory, HasUniqueSlug, SoftDeletes;
/**
* @return list<string>
*/
protected function slugScopeAttributes(): array
{
return ['portal', 'language'];
}
protected function slugFallback(): string
{
return 'pressemitteilung';
}
protected static function booted(): void
{
static::addGlobalScope(new PortalScope);
static::creating(function (self $pressRelease): void {
if (blank($pressRelease->placeholder_variant)) {
$seed = $pressRelease->uuid ?? $pressRelease->title ?? (string) now()->timestamp;
$pressRelease->placeholder_variant = PressReleasePlaceholder::fromSeed($seed)->value;
}
});
}
protected $fillable = [
'uuid',
'portal',
'user_id',
'company_id',
'category_id',
'language',
'title',
'subtitle',
'slug',
'text',
'boilerplate_override',
'placeholder_variant',
'backlink_url',
'keywords',
'status',
'classification',
'classified_at',
'content_score',
'content_tier',
'scored_at',
'hits',
'teaser_begin',
'teaser_end',
'no_export',
'published_at',
'scheduled_at',
'embargo_at',
'legacy_portal',
'legacy_id',
];
protected function casts(): array
{
return [
'portal' => Portal::class,
'placeholder_variant' => PressReleasePlaceholder::class,
'status' => PressReleaseStatus::class,
'classification' => PressReleaseClassification::class,
'classified_at' => 'datetime',
'content_score' => 'integer',
'content_tier' => PressReleaseContentTier::class,
'scored_at' => 'datetime',
'hits' => 'integer',
'teaser_begin' => 'integer',
'teaser_end' => 'integer',
'no_export' => 'boolean',
'published_at' => 'datetime',
'scheduled_at' => 'datetime',
'embargo_at' => 'datetime',
'deleted_at' => 'datetime',
];
}
/**
* Geplanter Veröffentlichungstermin. Die Anwendung läuft durchgängig in
* Europe/Berlin (config app.timezone), daher ist keine Umrechnung nötig.
*/
public function scheduledAtLocal(): ?Carbon
{
return $this->scheduled_at;
}
/**
* Sperrfrist (Embargo) in der Anwendungs-Zeitzone (Europe/Berlin).
*/
public function embargoAtLocal(): ?Carbon
{
return $this->embargo_at;
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function company(): BelongsTo
{
return $this->belongsTo(Company::class);
}
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
public function images(): HasMany
{
return $this->hasMany(PressReleaseImage::class);
}
public function attachments(): HasMany
{
return $this->hasMany(PressReleaseAttachment::class);
}
public function contacts(): BelongsToMany
{
return $this->belongsToMany(Contact::class, 'press_release_contact');
}
public function statusLogs(): HasMany
{
return $this->hasMany(PressReleaseStatusLog::class)->orderByDesc('created_at');
}
public function kiAudits(): HasMany
{
return $this->hasMany(KiAudit::class)->orderByDesc('created_at');
}
public function boosts(): HasMany
{
return $this->hasMany(Boost::class);
}
/**
* Aktuell geboostet (mindestens ein laufender Boost-Zeitraum)?
*/
public function isBoosted(): bool
{
return $this->boosts()->active()->exists();
}
/**
* Beschränkt auf PMs mit aktuell laufendem Boost — Basis für die
* Featured-Platzierung auf Start-/Branchenseite.
*/
public function scopeBoosted(Builder $query): Builder
{
return $query->whereHas('boosts', fn (Builder $q) => $q->active());
}
/**
* Beschränkt auf PMs, die dem User gehören (als Autor) oder zu einer ihm
* zugeordneten Firma. Bewusst ohne Portal-GlobalScope: ein Kunde darf
* seine eigenen PMs portalübergreifend sehen und bearbeiten.
*
* Single Source of Truth für den Kunden-Zugriff auf PMs — genutzt von der
* Übersicht, Detail-, Bearbeiten- und Nachweis-Ansicht.
*/
public function scopeAccessibleBy(Builder $query, User $user): Builder
{
return $query->withoutGlobalScopes()
->where(function (Builder $q) use ($user): void {
$q->where('user_id', $user->id);
$companyIds = $user->accessibleCompanyIds();
if ($companyIds !== []) {
$q->orWhereIn('company_id', $companyIds);
}
});
}
/**
* Display-ready text. Returns sanitized HTML for Phase-7+ PMs and
* <p>/<br>-wrapped legacy plain text for older imports.
*/
public function renderedText(): HtmlString
{
return app(PressReleaseHtmlSanitizer::class)->render($this->text);
}
public function plainTextLength(): int
{
return app(PressReleaseHtmlSanitizer::class)->plainTextLength($this->text);
}
}