presseportale/app/Services/Customer/CustomerStatusSummary.php
Kevin Adametz c7bd940f28 Optimierung Phase 0: Korrektheit & Security
Konsolidierter Entwicklungsplan aus den zwei Analyse-Dokumenten plus
Umsetzung der Phase-0-Massnahmen (Korrektheit/Security, je mit Tests):

0.1 BasicAuth: timing-sicherer Vergleich (hash_equals, beide Felder ohne
    Short-Circuit); Enabled-Check zur Laufzeit via config('auth.basic.*')
    statt env() im Bootstrap-Closure (greift jetzt unter config:cache);
    Config-Block + .env.example. Fund: auth.basic.* war nie als Config
    definiert, Gate war faktisch unkonfigurierbar.
0.2 Legacy-Invoice-"latest"-Abfrage zentralisiert (LegacyInvoice::
    scopeLatestFirst + User::latestLegacyInvoice); beide Consumer N+1-frei
    umgestellt; unterschiedliches null-Verhalten bewusst erhalten.
0.3 Payment-Option-Eligibility vereinheitlicht (period-aware, strikt):
    UserPaymentOption::scopeActiveNow/grandfatheredNow + User::
    hasActivePaymentOption; hasActiveBooking/hasUnlimitedPressReleaseQuota
    und ApiAccessEligibilityService darauf umgestellt; $hasGrandfathered-
    Mislabel behoben.
0.4 Theme->Portal-Vokabular: totes, projektfremdes ThemeMiddleware
    geloescht; Mapping in Portal::fromTheme() zentralisiert; fremden
    b2in-Default im ThemeServiceProvider auf Portal-Default korrigiert.
0.5 InvoiceNumberGenerator: Erst-Insert race-sicher via insertOrIgnore
    (Unique-Index auf circle existiert bereits). CreditWalletService war
    bereits abgesichert (Unique-Index + createOrFirst).

Tests: 4 neue Dateien, 5 bestehende auf gueltiges grandfathered_until
angepasst. Volle Suite gruen (793 passed, 1 skipped).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 08:09:02 +00:00

120 lines
3.7 KiB
PHP

<?php
namespace App\Services\Customer;
use App\Enums\Tier;
use App\Models\Plan;
use App\Models\User;
/**
* Read-only Statusüberblick für das immer verfügbare Buchungs-Widget im
* Header (aktuelle Buchung, verbleibendes PM-Kontingent, Credit-Guthaben).
*
* Single Source of Truth für die Gating-Logik bleibt das User-Modell; dieses
* DTO bündelt nur die fürs UI nötigen Werte, damit die Blade-Komponente keine
* eigene Geschäftslogik trägt.
*/
class CustomerStatusSummary
{
public function __construct(
public readonly Tier $tier,
public readonly ?string $planName,
public readonly ?string $billingInterval,
public readonly bool $hasActiveBooking,
public readonly bool $hasSubscription,
public readonly bool $hasGrandfathered,
public readonly int $openSinglePurchases,
public readonly bool $unlimitedQuota,
public readonly ?int $quotaTotal,
public readonly ?int $quotaRemaining,
public readonly int $creditBalance,
) {}
public static function fromUser(User $user): self
{
$plan = $user->currentPlan();
$subscription = $user->subscription();
$hasSubscription = (bool) $subscription?->valid();
$billingInterval = null;
if ($plan instanceof Plan && $subscription?->stripe_price) {
$billingInterval = $subscription->stripe_price === $plan->stripe_price_id_yearly
? 'yearly'
: 'monthly';
}
$hasGrandfathered = $user->userPaymentOptions()
->grandfatheredNow()
->exists();
return new self(
tier: $user->currentTier(),
planName: $plan?->name,
billingInterval: $billingInterval,
hasActiveBooking: $user->hasActiveBooking(),
hasSubscription: $hasSubscription,
hasGrandfathered: $hasGrandfathered,
openSinglePurchases: $user->singlePurchases()->grantingSubmission()->count(),
unlimitedQuota: $user->hasUnlimitedPressReleaseQuota(),
quotaTotal: $user->pressReleaseQuotaTotal(),
quotaRemaining: $user->pressReleaseQuotaRemaining(),
creditBalance: $user->creditBalance(),
);
}
public function hasCredits(): bool
{
return $this->creditBalance > 0;
}
/**
* Menschlich lesbares Etikett der aktuellen Buchung.
*/
public function bookingLabel(): string
{
if ($this->planName !== null) {
return $this->planName;
}
if ($this->hasGrandfathered) {
return __('Bestandstarif');
}
if ($this->openSinglePurchases > 0) {
return trans_choice(
'{1}:count Einzelbuchung|[2,*]:count Einzelbuchungen',
$this->openSinglePurchases,
['count' => $this->openSinglePurchases],
);
}
return __('Kein Abo');
}
public function billingIntervalLabel(): ?string
{
return match ($this->billingInterval) {
'monthly' => __('monatlich'),
'yearly' => __('jährlich'),
default => null,
};
}
/**
* Kompakter Text für das Trigger-Badge in der Topbar.
*/
public function badgeLabel(): string
{
$parts = [];
$parts[] = $this->unlimitedQuota
? __(':icon PM', ['icon' => '∞'])
: trans_choice('{0}:count PM|{1}:count PM|[2,*]:count PM', (int) $this->quotaRemaining, ['count' => (int) $this->quotaRemaining]);
if ($this->hasCredits()) {
$parts[] = __(':count Cr', ['count' => $this->creditBalance]);
}
return implode(' · ', $parts);
}
}