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>
This commit is contained in:
parent
c43ef6a5bd
commit
3da335388e
6 changed files with 139 additions and 38 deletions
|
|
@ -184,6 +184,28 @@ class PressRelease extends Model
|
||||||
return $query->whereHas('boosts', fn (Builder $q) => $q->active());
|
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
|
* Display-ready text. Returns sanitized HTML for Phase-7+ PMs and
|
||||||
* <p>/<br>-wrapped legacy plain text for older imports.
|
* <p>/<br>-wrapped legacy plain text for older imports.
|
||||||
|
|
|
||||||
|
|
@ -117,25 +117,45 @@ class User extends Authenticatable implements MustVerifyEmail
|
||||||
return (bool) $this->billingAddress?->isComplete();
|
return (bool) $this->billingAddress?->isComplete();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-Request-Memoisierung: Tarif und Unlimited-Flag werden pro Render
|
||||||
|
* mehrfach abgefragt (u. a. vom immer sichtbaren Status-Widget und der
|
||||||
|
* Buchungsseite). Beide ändern sich innerhalb eines Requests nicht über
|
||||||
|
* In-App-Aktionen (Abo läuft über Stripe-Redirect, Bestandstarif über
|
||||||
|
* CLI), daher ist die Memoisierung sicher; `fresh()` liefert eine neue
|
||||||
|
* Instanz und setzt den Cache zurück.
|
||||||
|
*/
|
||||||
|
private bool $currentPlanResolved = false;
|
||||||
|
|
||||||
|
private ?Plan $cachedCurrentPlan = null;
|
||||||
|
|
||||||
|
private ?bool $cachedHasUnlimitedQuota = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Der Tarif des aktiven Stripe-Abos, aufgelöst über die in `plans`
|
* Der Tarif des aktiven Stripe-Abos, aufgelöst über die in `plans`
|
||||||
* gepflegten Stripe-Preis-IDs. Null ohne (gültiges) Abo.
|
* gepflegten Stripe-Preis-IDs. Null ohne (gültiges) Abo.
|
||||||
*/
|
*/
|
||||||
public function currentPlan(): ?Plan
|
public function currentPlan(): ?Plan
|
||||||
{
|
{
|
||||||
|
if ($this->currentPlanResolved) {
|
||||||
|
return $this->cachedCurrentPlan;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->currentPlanResolved = true;
|
||||||
|
|
||||||
$subscription = $this->subscription();
|
$subscription = $this->subscription();
|
||||||
|
|
||||||
if (! $subscription?->valid()) {
|
if (! $subscription?->valid()) {
|
||||||
return null;
|
return $this->cachedCurrentPlan = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
$priceId = $subscription->stripe_price;
|
$priceId = $subscription->stripe_price;
|
||||||
|
|
||||||
if (! $priceId) {
|
if (! $priceId) {
|
||||||
return null;
|
return $this->cachedCurrentPlan = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return Plan::query()
|
return $this->cachedCurrentPlan = Plan::query()
|
||||||
->where('stripe_price_id_monthly', $priceId)
|
->where('stripe_price_id_monthly', $priceId)
|
||||||
->orWhere('stripe_price_id_yearly', $priceId)
|
->orWhere('stripe_price_id_yearly', $priceId)
|
||||||
->first();
|
->first();
|
||||||
|
|
@ -160,11 +180,15 @@ class User extends Authenticatable implements MustVerifyEmail
|
||||||
*/
|
*/
|
||||||
public function hasUnlimitedPressReleaseQuota(): bool
|
public function hasUnlimitedPressReleaseQuota(): bool
|
||||||
{
|
{
|
||||||
if (! config('billing.enforce_booking')) {
|
if ($this->cachedHasUnlimitedQuota !== null) {
|
||||||
return true;
|
return $this->cachedHasUnlimitedQuota;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->userPaymentOptions()
|
if (! config('billing.enforce_booking')) {
|
||||||
|
return $this->cachedHasUnlimitedQuota = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->cachedHasUnlimitedQuota = $this->userPaymentOptions()
|
||||||
->whereIn('status', [
|
->whereIn('status', [
|
||||||
UserPaymentOptionStatus::Active->value,
|
UserPaymentOptionStatus::Active->value,
|
||||||
UserPaymentOptionStatus::Grandfathered->value,
|
UserPaymentOptionStatus::Grandfathered->value,
|
||||||
|
|
|
||||||
|
|
@ -684,16 +684,7 @@ new #[Layout('components.layouts.app'), Title('Pressemitteilung bearbeiten')] cl
|
||||||
{
|
{
|
||||||
// Pro Livewire-Request memoisiert: mount(), with() und save() greifen
|
// Pro Livewire-Request memoisiert: mount(), with() und save() greifen
|
||||||
// sonst jeweils mit einer eigenen Query auf dieselbe PM zu.
|
// sonst jeweils mit einer eigenen Query auf dieselbe PM zu.
|
||||||
$user = auth()->user();
|
return $this->cachedPressRelease ??= PressRelease::accessibleBy(auth()->user())
|
||||||
|
|
||||||
return $this->cachedPressRelease ??= PressRelease::withoutGlobalScopes()
|
|
||||||
->where(function ($q) use ($user): void {
|
|
||||||
$q->where('user_id', $user->id);
|
|
||||||
$companyIds = $user->accessibleCompanyIds();
|
|
||||||
if ($companyIds !== []) {
|
|
||||||
$q->orWhereIn('company_id', $companyIds);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
->findOrFail($this->id);
|
->findOrFail($this->id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -110,19 +110,11 @@ new #[Layout('components.layouts.app'), Title('Meine Pressemitteilungen')] class
|
||||||
|
|
||||||
public function with(): array
|
public function with(): array
|
||||||
{
|
{
|
||||||
$userId = auth()->id();
|
|
||||||
$context = app(CustomerCompanyContext::class);
|
$context = app(CustomerCompanyContext::class);
|
||||||
$selectedCompanyId = $context->selectedCompanyId(auth()->user());
|
$selectedCompanyId = $context->selectedCompanyId(auth()->user());
|
||||||
// Firmen-Scope: eigene PMs (Autor) ODER PMs der zugeordneten Firmen.
|
|
||||||
$accessibleCompanyIds = auth()->user()->accessibleCompanyIds();
|
|
||||||
|
|
||||||
$base = PressRelease::withoutGlobalScopes()
|
// Firmen-Scope: eigene PMs (Autor) ODER PMs der zugeordneten Firmen.
|
||||||
->where(function ($q) use ($userId, $accessibleCompanyIds): void {
|
$base = PressRelease::accessibleBy(auth()->user())
|
||||||
$q->where('user_id', $userId);
|
|
||||||
if ($accessibleCompanyIds !== []) {
|
|
||||||
$q->orWhereIn('company_id', $accessibleCompanyIds);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
->when($selectedCompanyId !== null, fn($q) => $q->where('company_id', $selectedCompanyId))
|
->when($selectedCompanyId !== null, fn($q) => $q->where('company_id', $selectedCompanyId))
|
||||||
->when($selectedCompanyId === null && $this->companyFilter === 'assigned', fn($q) => $q->whereNotNull('company_id'))
|
->when($selectedCompanyId === null && $this->companyFilter === 'assigned', fn($q) => $q->whereNotNull('company_id'))
|
||||||
->when($selectedCompanyId === null && $this->companyFilter === 'unassigned', fn($q) => $q->whereNull('company_id'));
|
->when($selectedCompanyId === null && $this->companyFilter === 'unassigned', fn($q) => $q->whereNull('company_id'));
|
||||||
|
|
|
||||||
|
|
@ -158,7 +158,7 @@ new #[Layout('components.layouts.app'), Title('Pressemitteilung')] class extends
|
||||||
$cover = app(PressReleaseCoverImage::class);
|
$cover = app(PressReleaseCoverImage::class);
|
||||||
$user = auth()->user();
|
$user = auth()->user();
|
||||||
|
|
||||||
$company = $pr->company?->loadCount(['pressReleases', 'contacts']);
|
$company = $pr->company;
|
||||||
|
|
||||||
$boostService = app(BoostService::class);
|
$boostService = app(BoostService::class);
|
||||||
$proofService = app(ProofPdfService::class);
|
$proofService = app(ProofPdfService::class);
|
||||||
|
|
@ -246,20 +246,19 @@ new #[Layout('components.layouts.app'), Title('Pressemitteilung')] class extends
|
||||||
return implode(' · ', $parts);
|
return implode(' · ', $parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ?PressRelease $cachedPressRelease = null;
|
||||||
|
|
||||||
private function getMyPR(): PressRelease
|
private function getMyPR(): PressRelease
|
||||||
{
|
{
|
||||||
$user = auth()->user();
|
// Pro Livewire-Request memoisiert: mount(), with() und die Add-on-
|
||||||
|
// Aktionen rufen getMyPR() sonst jeweils mit der vollen Eager-Load-
|
||||||
return PressRelease::withoutGlobalScopes()
|
// Query erneut auf. Firmen-Kennzahlen direkt mit eager laden, statt
|
||||||
->where(function ($q) use ($user): void {
|
// sie nachträglich per loadCount() nachzuziehen.
|
||||||
$q->where('user_id', $user->id);
|
return $this->cachedPressRelease ??= PressRelease::accessibleBy(auth()->user())
|
||||||
$companyIds = $user->accessibleCompanyIds();
|
|
||||||
if ($companyIds !== []) {
|
|
||||||
$q->orWhereIn('company_id', $companyIds);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
->with([
|
->with([
|
||||||
'company:id,name,email,phone,address,portal,logo_path,legacy_portal,is_active,type',
|
'company' => fn ($query) => $query
|
||||||
|
->select(['id', 'name', 'email', 'phone', 'address', 'portal', 'logo_path', 'legacy_portal', 'is_active', 'type'])
|
||||||
|
->withCount(['pressReleases', 'contacts']),
|
||||||
'category.translations',
|
'category.translations',
|
||||||
'contacts' => fn ($query) => $query
|
'contacts' => fn ($query) => $query
|
||||||
->withoutGlobalScopes()
|
->withoutGlobalScopes()
|
||||||
|
|
|
||||||
73
tests/Feature/PressReleaseAccessScopeTest.php
Normal file
73
tests/Feature/PressReleaseAccessScopeTest.php
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Enums\Portal;
|
||||||
|
use App\Models\Company;
|
||||||
|
use App\Models\PressRelease;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\CurrentPortalContext;
|
||||||
|
use Database\Seeders\RolesAndPermissionsSeeder;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
beforeEach(function (): void {
|
||||||
|
/** @var TestCase $this */
|
||||||
|
$this->seed(RolesAndPermissionsSeeder::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accessibleBy includes a users own authored press release', function () {
|
||||||
|
$user = User::factory()->create();
|
||||||
|
$pr = PressRelease::factory()->create(['user_id' => $user->id, 'company_id' => null]);
|
||||||
|
|
||||||
|
$ids = PressRelease::accessibleBy($user)->pluck('id');
|
||||||
|
|
||||||
|
expect($ids)->toContain($pr->id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accessibleBy includes press releases of an assigned company', function () {
|
||||||
|
$user = User::factory()->create();
|
||||||
|
$company = Company::factory()->presseecho()->create();
|
||||||
|
$user->companies()->attach($company->id, ['role' => 'owner']);
|
||||||
|
|
||||||
|
$other = User::factory()->create();
|
||||||
|
$pr = PressRelease::factory()->create([
|
||||||
|
'user_id' => $other->id,
|
||||||
|
'company_id' => $company->id,
|
||||||
|
'portal' => $company->portal->value,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$ids = PressRelease::accessibleBy($user)->pluck('id');
|
||||||
|
|
||||||
|
expect($ids)->toContain($pr->id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accessibleBy excludes press releases of strangers and unrelated companies', function () {
|
||||||
|
$user = User::factory()->create();
|
||||||
|
$stranger = User::factory()->create();
|
||||||
|
$foreignCompany = Company::factory()->presseecho()->create();
|
||||||
|
|
||||||
|
$foreignPr = PressRelease::factory()->create([
|
||||||
|
'user_id' => $stranger->id,
|
||||||
|
'company_id' => $foreignCompany->id,
|
||||||
|
'portal' => $foreignCompany->portal->value,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$ids = PressRelease::accessibleBy($user)->pluck('id');
|
||||||
|
|
||||||
|
expect($ids)->not->toContain($foreignPr->id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accessibleBy bypasses the portal global scope so own PMs are visible cross-portal', function () {
|
||||||
|
$user = User::factory()->create();
|
||||||
|
$pr = PressRelease::factory()->create([
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'company_id' => null,
|
||||||
|
'portal' => Portal::Businessportal24->value,
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Simuliert eingeschränkten Portal-Kontext (Presseecho); der Scope muss
|
||||||
|
// die eigene PM dennoch finden, weil er die GlobalScopes entfernt.
|
||||||
|
CurrentPortalContext::set(Portal::Presseecho);
|
||||||
|
|
||||||
|
$found = PressRelease::accessibleBy($user)->find($pr->id);
|
||||||
|
|
||||||
|
expect($found)->not->toBeNull();
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue