resetErrorBag('companyId'); } public function updatedPublishMode(): void { $this->syncScheduledAt(); if ($this->publishMode === 'now') { $this->scheduledDate = null; $this->scheduledTime = null; $this->scheduledAt = null; $this->resetErrorBag(['scheduledDate', 'scheduledTime', 'scheduledAt']); } } public function updatedScheduledDate(): void { $this->syncScheduledAt(); $this->validateScheduledAtWhenReady(); } public function updatedScheduledTime(): void { $this->syncScheduledAt(); $this->validateScheduledAtWhenReady(); } public function updatedCompanyId(): void { if (!$this->companyId) { $this->contactId = null; return; } $contactStillValid = $this->companyContact((int) $this->contactId, (int) $this->companyId); if (!$contactStillValid) { $this->contactId = $this->defaultContactIdFor((int) $this->companyId); } unset($this->presubmitChecks); } public function updatedTitle(): void { $this->resetErrorBag('title'); } public function addTag(string $tag): void { $tag = trim($tag); if ($tag === '') { return; } $existing = $this->tagsArray(); if (count($existing) >= 5) { return; } if (in_array($tag, $existing, true)) { return; } $existing[] = $tag; $this->keywords = implode(', ', $existing); unset($this->tags, $this->presubmitChecks); } public function removeTag(string $tag): void { $existing = array_values(array_filter($this->tagsArray(), fn(string $existingTag): bool => $existingTag !== $tag)); $this->keywords = implode(', ', $existing); unset($this->tags, $this->presubmitChecks); } /** * Single Source of Truth für die Validierungsregeln. Ermöglicht * Live-Re-Validation via updated()-Hook ohne Duplikation. * * @return array> */ protected function formRules(): array { $rules = [ 'portal' => ['required', Rule::in(array_map(fn(Portal $p) => $p->value, Portal::cases()))], 'language' => ['required', Rule::in(['de', 'en'])], 'companyId' => ['required', 'integer', Rule::exists('companies', 'id')], 'categoryId' => ['required', 'integer', Rule::exists('categories', 'id')], 'contactId' => ['nullable', 'integer'], 'title' => ['required', 'string', 'min:5', 'max:255'], 'subtitle' => ['nullable', 'string', 'max:255'], 'text' => ['required', 'string', 'min:50'], 'keywords' => ['nullable', 'string', 'max:255'], 'backlinkUrl' => ['nullable', 'url', 'max:255'], 'boilerplateOverride' => ['nullable', 'string', 'max:5000'], 'publishMode' => ['required', Rule::in(['now', 'scheduled'])], ]; if ($this->publishMode === 'scheduled') { $rules['scheduledDate'] = ['required', 'date']; $rules['scheduledTime'] = ['required', 'date_format:H:i']; $rules['scheduledAt'] = [ 'required', 'date', // Termin wird in Europe/Berlin erfasst; deshalb hier zeitzonen- // bewusst prüfen statt über die naive `after:`-Regel. function (string $attribute, mixed $value, \Closure $fail): void { $scheduledAt = $this->scheduledAtUtc(); if ($scheduledAt === null || $scheduledAt->lessThanOrEqualTo(now()->addMinutes(5))) { $fail(__('Der Veröffentlichungstermin muss mindestens 5 Minuten in der Zukunft liegen.')); } }, ]; } else { $rules['scheduledDate'] = ['nullable']; $rules['scheduledTime'] = ['nullable']; $rules['scheduledAt'] = ['nullable']; } $rules['embargoAt'] = ['nullable']; return $rules; } protected function syncScheduledAt(): void { if ($this->publishMode !== 'scheduled') { $this->scheduledAt = null; return; } if (blank($this->scheduledDate) && blank($this->scheduledTime) && filled($this->scheduledAt)) { $scheduledAt = \Carbon\Carbon::parse($this->scheduledAt); $this->scheduledDate = $scheduledAt->format('Y-m-d'); $this->scheduledTime = $scheduledAt->format('H:i'); return; } if (blank($this->scheduledDate) || blank($this->scheduledTime)) { $this->scheduledAt = null; return; } $this->scheduledAt = "{$this->scheduledDate}T{$this->scheduledTime}"; } /** * Wandelt den in Europe/Berlin erfassten Termin in den UTC-Zeitpunkt, * wie er in der Datenbank gespeichert wird. Null, wenn kein Termin gesetzt. */ protected function scheduledAtUtc(): ?\Carbon\Carbon { if (blank($this->scheduledAt)) { return null; } return \Carbon\Carbon::parse($this->scheduledAt, PressRelease::DISPLAY_TIMEZONE)->utc(); } protected function validateScheduledAtWhenReady(): void { if (blank($this->scheduledAt)) { return; } $this->resetErrorBag('scheduledAt'); $scheduledAt = $this->scheduledAtUtc(); if ($scheduledAt === null || $scheduledAt->lessThanOrEqualTo(now()->addMinutes(5))) { $this->addError('scheduledAt', __('Der Veröffentlichungstermin muss mindestens 5 Minuten in der Zukunft liegen.')); return; } try { $this->validateOnly('scheduledAt', $this->formRules()); } catch (\Illuminate\Validation\ValidationException) { // Termin bleibt invalid; Bag wird automatisch befüllt. } } /** * Live-Re-Validation für bereits invalide Felder. * * Die Termin-Synchronisierung liegt vollständig in den spezifischen * `updated{PublishMode,ScheduledDate,ScheduledTime}`-Hooks; hier bleibt * nur die generische Re-Validierung bereits fehlerhafter Felder. */ public function updated(string $property): void { if (!$this->getErrorBag()->has($property)) { return; } try { $this->validateOnly($property, $this->formRules()); } catch (\Illuminate\Validation\ValidationException) { // Field bleibt invalid; Bag wird automatisch befüllt. } } protected function notifyValidationError(?\Illuminate\Validation\ValidationException $exception = null): void { $count = $exception ? array_sum(array_map('count', $exception->errors())) : count($this->getErrorBag()->all()); Flux::toast(heading: __('Bitte Eingaben prüfen'), text: $count > 1 ? __(':count Felder benötigen deine Aufmerksamkeit.', ['count' => $count]) : __('Ein Feld benötigt deine Aufmerksamkeit.'), variant: 'danger', duration: 6000); } public function save(string $submitStatus = 'draft'): void { $this->syncScheduledAt(); $this->useEmbargo = false; $this->embargoAt = null; try { $this->validate($this->formRules()); } catch (\Illuminate\Validation\ValidationException $e) { $this->notifyValidationError($e); throw $e; } $status = match ($submitStatus) { 'review' => PressReleaseStatus::Review, default => PressReleaseStatus::Draft, }; $slug = new PressRelease()->generateUniqueSlug($this->title, [ 'portal' => $this->portal, 'language' => $this->language, ]); $cleanText = app(PressReleaseHtmlSanitizer::class)->clean($this->text); $pr = PressRelease::query()->create([ 'uuid' => (string) Str::uuid(), 'portal' => $this->portal, 'language' => $this->language, 'user_id' => auth()->id(), 'company_id' => (int) $this->companyId, 'category_id' => (int) $this->categoryId, 'title' => $this->title, 'subtitle' => trim($this->subtitle) ?: null, 'slug' => $slug, 'text' => $cleanText, 'boilerplate_override' => $this->useBoilerplateOverride && trim($this->boilerplateOverride) !== '' ? trim($this->boilerplateOverride) : null, 'keywords' => $this->keywords ?: null, 'backlink_url' => $this->backlinkUrl ?: null, 'scheduled_at' => $this->publishMode === 'scheduled' ? $this->scheduledAtUtc() : null, 'embargo_at' => null, 'status' => $status->value, 'no_export' => $this->noExport, ]); if ($this->contactId) { $contact = $this->companyContact((int) $this->contactId, (int) $this->companyId); if ($contact) { $pr->contacts()->sync([$contact->id]); } } Flux::toast(heading: $status === PressReleaseStatus::Review ? __('Eingereicht') : __('Entwurf gespeichert'), text: $status === PressReleaseStatus::Review ? __('Pressemitteilung zur Prüfung eingereicht.') : __('Pressemitteilung als Entwurf gespeichert.'), variant: 'success'); $this->redirect(route('admin.press-releases.edit', $pr->id), navigate: true); } public function with(): array { $term = Portal::stripTrailingAbbreviation($this->companySearch); $companies = Company::withoutGlobalScopes() ->when(filled($term), function ($q) use ($term): void { if ($this->supportsFullTextSearch($term)) { $q->whereFullText(['name', 'email', 'slug'], $term); return; } $q->where('name', 'like', '%' . $term . '%')->orWhere('slug', 'like', '%' . $term . '%'); }) ->when(blank($term) && $this->companyId, fn($q) => $q->whereIn('id', [(int) $this->companyId])) ->when(blank($term) && !$this->companyId, fn($q) => $q->whereRaw('0 = 1')) ->orderBy('name') ->limit(50) ->get(['id', 'name']); $selectedCompany = $this->companyId ? Company::withoutGlobalScopes()->find((int) $this->companyId) : null; return [ 'companies' => $companies, 'categories' => $this->categoryOptions(), 'portalOptions' => array_filter(Portal::cases(), fn(Portal $p) => $p !== Portal::Both), 'selectedCompany' => $selectedCompany, 'selectedCompanyContacts' => $selectedCompany ? $this->companyContacts((int) $selectedCompany->id) : Contact::query()->whereRaw('0 = 1')->get(), 'tagSuggestions' => $this->tagSuggestionsFor($selectedCompany), ]; } #[Computed] public function tags(): array { return $this->tagsArray(); } #[Computed] public function presubmitChecks(): array { $titleLen = mb_strlen(trim($this->title)); $textLen = app(PressReleaseHtmlSanitizer::class)->plainTextLength($this->text); $tagsCount = count($this->tagsArray()); return [ [ 'key' => 'title', 'status' => $titleLen >= 5 ? 'ok' : 'err', 'label' => __('Titel vorhanden'), 'sub' => $titleLen > 0 ? __(':n Zeichen', ['n' => $titleLen]) : __('Noch leer'), ], [ 'key' => 'text', 'status' => $textLen >= 600 ? 'ok' : ($textLen >= 50 ? 'warn' : 'err'), 'label' => __('Mindestlänge Fließtext erreicht'), 'sub' => __(':n / 600 Zeichen empfohlen', ['n' => number_format($textLen, 0, ',', '.')]), ], [ 'key' => 'company', 'status' => $this->companyId ? 'ok' : 'err', 'label' => __('Firma zugeordnet'), 'sub' => $this->companyId ? '' : __('Keine Firma gewählt'), ], [ 'key' => 'category', 'status' => $this->categoryId ? 'ok' : 'err', 'label' => __('Kategorie gewählt'), 'sub' => $this->categoryId ? '' : __('Kategorie ist Pflicht'), ], [ 'key' => 'contact', 'status' => $this->contactId ? 'ok' : 'warn', 'label' => __('Pressekontakt zugeordnet'), 'sub' => $this->contactId ? '' : __('empfohlen — Journalisten greifen direkt zum Hörer'), ], [ 'key' => 'tags', 'status' => $tagsCount >= 1 ? 'ok' : 'warn', 'label' => __('Themen-Tags vergeben'), 'sub' => $tagsCount >= 1 ? trans_choice('{1}:n Tag|[2,*]:n Tags', $tagsCount, ['n' => $tagsCount]) : __('empfohlen für SEO & Auffindbarkeit'), ], ]; } /** * @return list */ private function tagsArray(): array { if (trim($this->keywords) === '') { return []; } return collect(explode(',', $this->keywords)) ->map(fn(string $tag): string => trim($tag)) ->filter() ->unique() ->values() ->all(); } private function defaultContactIdFor(int $companyId): ?int { if ($companyId <= 0) { return null; } return $this->companyContacts($companyId)->first()?->id; } /** * @return Collection */ private function companyContacts(int $companyId): Collection { return Contact::withoutGlobalScopes() ->where('company_id', $companyId) ->orderBy('last_name') ->orderBy('first_name') ->get(['id', 'company_id', 'first_name', 'last_name', 'responsibility', 'phone', 'email']); } private function companyContact(int $contactId, int $companyId): ?Contact { if ($contactId <= 0 || $companyId <= 0) { return null; } return Contact::withoutGlobalScopes()->where('company_id', $companyId)->whereKey($contactId)->first(); } /** * @return list */ private function tagSuggestionsFor(?Company $company): array { $defaults = [__('Mittelstand'), __('Unternehmen'), __('Eröffnung'), __('Innovation'), __('Nachhaltigkeit')]; if (!$company) { return $defaults; } return array_values(array_unique(array_filter([$company->portal?->label(), $company->country_code === 'DE' ? __('Deutschland') : null, ...$defaults]))); } private function categoryOptions(): Collection { return app(AdminPerformanceCache::class)->remember(AdminPerformanceCache::ActiveCategoryOptions, AdminPerformanceCache::OptionsTtl, fn() => Category::query()->with('translations')->where('is_active', true)->orderBy('id')->get()); } private function supportsFullTextSearch(string $term): bool { return mb_strlen($term) >= 3 && in_array(DB::connection()->getDriverName(), ['mysql', 'pgsql'], true); } }; ?>
{{-- ============== PAGE HEADER ============== --}}
{{ __('Admin Backend') }} {{ __('Content · Neu anlegen') }}

{{ __('Neue Pressemitteilung') }}

{{ __('Schreibfläche links, Steuerung rechts. Pflichtfelder werden rechts in der Checkliste angezeigt.') }}

{{ __('Zurück') }}
{{-- ============== 2-COLUMN GRID ============== --}}
{{-- =================== LINKS: SCHREIBFLÄCHE =================== --}}
{{-- 1) FIRMA-SELEKTOR --}}
{{ __('Für Firma') }} * @foreach ($companies as $company) {{ $company->name }} @if ($company->portal) ({{ $company->portal->abbreviation() }}) @endif @endforeach @if (blank(trim($companySearch))) {{ __('Mindestens 1 Zeichen eingeben…') }} @else {{ __('Keine Firma gefunden.') }} @endif
{{ __('Boilerplate und Pressekontakt werden bei Wechsel angepasst.') }} @if ($selectedCompany) {{ __('Firmenprofil') }} @endif
{{-- 2) TITEL --}}
{{ __('Titel / Headline') }} *
@php $titleLen = mb_strlen($title); $titleClass = $titleLen >= 40 && $titleLen <= 90 ? 'good' : ($titleLen > 0 ? 'warn' : ''); $titleBar = min(100, max(0, ($titleLen / 100) * 100)); @endphp {{ $titleLen }} / 100 {{ __('KI-Titel · bald') }}

{{ __('40–90 Zeichen empfohlen. Konkret, ohne Marketing-Floskeln.') }}

{{-- 3) SUBTITLE --}}
{{ __('Untertitel') }} — {{ __('optional') }} @php $subLen = mb_strlen($subtitle); $subBar = min(100, max(0, ($subLen / 200) * 100)); @endphp {{ $subLen }} / 200
{{-- 4) FLIESSTEXT --}}
{{ __('Fließtext') }} *
@php $textLen = app( \App\Services\PressRelease\PressReleaseHtmlSanitizer::class, )->plainTextLength($text); $textClass = $textLen >= 600 ? 'good' : ($textLen >= 50 ? 'warn' : ''); $textBar = min(100, max(0, ($textLen / 3500) * 100)); @endphp {{ number_format($textLen, 0, ',', '.') }} / 3.500 Z. {{ __('KI-Lektorat · bald') }}
{{ __('KI-Lektorat') }} {{ __('liest Korrektur, schlägt Kürzungen vor und prüft auf werbliche Sprache. Erscheint hier inline — bald verfügbar.') }}
{{-- 5) BOILERPLATE --}}
{{ __('Über das Unternehmen') }} — {{ __('Boilerplate aus Firma') }}
@if ($selectedCompany?->boilerplate)

{!! nl2br(e($selectedCompany->boilerplate)) !!}

@if ($selectedCompany->website)

{{ __('Web') }}: {{ $selectedCompany->website }}

@endif
@else
{{ __('Für diese Firma ist noch kein Boilerplate-Text hinterlegt. Du kannst entweder einen Override-Text für diese PM setzen oder das Firmenprofil ergänzen.') }}
@endif @if ($useBoilerplateOverride)
@endif

{{ __('Wird automatisch unter jeder Pressemitteilung dieser Firma angefügt. Pro PM editierbar.') }}

{{-- /Schreibfläche --}} {{-- =================== RECHTS: SETTINGS-SIDEBAR =================== --}}