Plugin-System; Neuigkeiten und Termine als mitgelieferte Plugins

- Plugins nach WordPress-Prinzip: plugin.json-Manifest mit Versions- und
  Abhängigkeitsprüfung, eigenes PSR-4-Autoloading, register()/boot(),
  activate()/deactivate()/uninstall(), Migrationen, Routen und Views je Plugin
- plugins-core/ (mitgeliefert, aktiv bis zur Deaktivierung) und plugins/
  (Kunden-Plugins, geschützt vor Updates, inaktiv bis zur Aktivierung)
- Zustand in storage/app/plugins.json – Laden ohne Datenbankabfrage
- Wiederherstellungsmodus: Ausnahmen und Fatal Errors beim Laden
  deaktivieren das Plugin, das Portal bleibt erreichbar
- Hooks (Actions/Filter mit Prioritäten) und Registries für Navigation,
  Startseiten-Kacheln, Rechte und Admin-Seiten (Filament-Discovery)
- Admin-Seite „Plugins“: aktivieren, deaktivieren, per ZIP installieren
  (ZIP-Slip-Schutz), löschen mit oder ohne Daten; abschaltbar per
  INHAUS_DISALLOW_FILE_MODS
- Startseite komplett aus Kacheln; Plugin-Seiten als „slug::Seite“
- Version 0.3.0

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 07:06:16 +00:00
parent cc0020458f
commit 28ef1e4a20
155 changed files with 2762 additions and 573 deletions

View file

@ -0,0 +1,47 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('news_categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->string('description', 500)->nullable();
$table->unsignedInteger('sort')->default(0);
$table->timestamps();
});
Schema::create('news_posts', function (Blueprint $table) {
$table->id();
$table->foreignId('category_id')->nullable()->constrained('news_categories')->nullOnDelete();
$table->foreignId('author_id')->nullable()->constrained('users')->nullOnDelete();
$table->string('title');
$table->string('slug')->unique();
$table->text('teaser')->nullable();
$table->longText('body')->nullable();
// Beim Speichern gerendert und bereinigt – die Ausgabe kostet keine Rechenzeit.
$table->longText('body_html')->nullable();
$table->unsignedSmallInteger('reading_minutes')->default(1);
$table->string('cover_path')->nullable();
$table->boolean('is_featured')->default(false);
$table->timestamp('published_at')->nullable();
$table->timestamps();
$table->index('published_at');
$table->index(['category_id', 'published_at']);
$table->index(['is_featured', 'published_at']);
});
}
public function down(): void
{
Schema::dropIfExists('news_posts');
Schema::dropIfExists('news_categories');
}
};

View file

@ -0,0 +1,13 @@
{
"slug": "news",
"name": "Neuigkeiten",
"version": "1.0.0",
"description": "Beiträge mit Kategorien, Titelbildern und Hervorhebung auf der Startseite.",
"author": "Inhaus",
"namespace": "Inhaus\\Plugins\\News\\",
"class": "Inhaus\\Plugins\\News\\NewsPlugin",
"requires": {
"core": ">=0.3.0",
"php": ">=8.3"
}
}

View file

@ -0,0 +1,9 @@
<script setup>
defineProps({
category: { type: Object, default: null },
});
</script>
<template>
<span v-if="category" class="text-[11px] font-semibold tracking-wide text-brand-text uppercase">{{ category.name }}</span>
</template>

View file

@ -0,0 +1,107 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { Link } from '@inertiajs/vue3';
import { ArrowRight, ChevronLeft, ChevronRight, Pause, Play } from '@lucide/vue';
const props = defineProps({
posts: { type: Array, required: true },
});
const index = ref(0);
const paused = ref(false);
const current = computed(() => props.posts[index.value]);
let timer = null;
function go(to) {
index.value = (to + props.posts.length) % props.posts.length;
}
function start() {
stop();
if (props.posts.length > 1 && !paused.value && !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
timer = setInterval(() => go(index.value + 1), 7000);
}
}
function stop() {
clearInterval(timer);
}
function togglePause() {
paused.value = !paused.value;
start();
}
onMounted(start);
onBeforeUnmount(stop);
</script>
<template>
<section
class="relative isolate aspect-[16/10] overflow-hidden rounded-lg bg-brand-950 text-white sm:aspect-[16/9] lg:aspect-auto lg:h-full lg:min-h-[400px]"
aria-roledescription="Karussell"
aria-label="Hervorgehobene Neuigkeiten"
@mouseenter="stop"
@mouseleave="start"
@focusin="stop"
@focusout="start"
>
<TransitionGroup
enter-active-class="transition-opacity duration-700"
leave-active-class="transition-opacity duration-700 absolute inset-0"
enter-from-class="opacity-0"
leave-to-class="opacity-0"
>
<img
v-for="(post, i) in posts"
v-show="i === index"
:key="post.id"
:src="post.cover_url"
alt=""
class="absolute inset-0 -z-10 size-full object-cover"
/>
</TransitionGroup>
<div class="absolute inset-0 -z-10 bg-gradient-to-t from-black/80 via-black/35 to-black/5 sm:bg-gradient-to-r sm:from-black/75 sm:via-black/40 sm:to-transparent" />
<div class="flex h-full flex-col justify-end p-6 sm:max-w-[65%] sm:justify-center sm:p-10" aria-live="polite">
<span v-if="current.category" class="mb-3 w-fit rounded-sm bg-brand px-2 py-0.5 text-[11px] font-semibold tracking-wide text-brand-foreground uppercase">
{{ current.category.name }}
</span>
<h2 class="text-2xl leading-tight font-semibold tracking-tight sm:text-[32px]">{{ current.title }}</h2>
<p v-if="current.teaser" class="mt-3 line-clamp-3 hidden text-[15px] text-white/85 sm:block">{{ current.teaser }}</p>
<Link
:href="`/neuigkeiten/${current.slug}`"
class="mt-5 inline-flex w-fit items-center gap-2 rounded-md bg-brand px-4 py-2.5 text-sm font-medium text-brand-foreground transition-colors hover:bg-brand-700"
>
Mehr erfahren
<ArrowRight class="size-4" />
</Link>
</div>
<div v-if="posts.length > 1" class="absolute right-4 bottom-4 flex items-center gap-2 sm:right-6 sm:bottom-6">
<button type="button" class="grid size-9 place-items-center rounded-full bg-black/35 hover:bg-black/55" aria-label="Vorheriger Beitrag" @click="go(index - 1)">
<ChevronLeft class="size-5" />
</button>
<div class="flex items-center gap-1.5 px-1">
<button
v-for="(post, i) in posts"
:key="post.id"
type="button"
class="h-1.5 rounded-full transition-all"
:class="i === index ? 'w-6 bg-white' : 'w-1.5 bg-white/50 hover:bg-white/80'"
:aria-label="`Beitrag ${i + 1} von ${posts.length}`"
:aria-current="i === index"
@click="go(i)"
/>
</div>
<button type="button" class="grid size-9 place-items-center rounded-full bg-black/35 hover:bg-black/55" aria-label="Nächster Beitrag" @click="go(index + 1)">
<ChevronRight class="size-5" />
</button>
<button type="button" class="grid size-9 place-items-center rounded-full bg-black/35 hover:bg-black/55" :aria-label="paused ? 'Automatisch weiterblättern' : 'Anhalten'" @click="togglePause">
<Play v-if="paused" class="size-4" />
<Pause v-else class="size-4" />
</button>
</div>
</section>
</template>

View file

@ -0,0 +1,22 @@
<script setup>
import { Link } from '@inertiajs/vue3';
import CategoryLabel from './CategoryLabel.vue';
import NewsImage from './NewsImage.vue';
import { formatShortDate } from '@/lib/format';
defineProps({
post: { type: Object, required: true },
});
</script>
<template>
<Link :href="`/neuigkeiten/${post.slug}`" class="group flex h-full flex-col overflow-hidden rounded-lg border bg-card transition-shadow hover:shadow-md">
<NewsImage :src="post.thumb_url" :alt="post.title" />
<div class="flex flex-1 flex-col p-4">
<CategoryLabel :category="post.category" />
<h3 class="mt-1 line-clamp-2 text-[15px] leading-snug font-semibold group-hover:underline">{{ post.title }}</h3>
<p v-if="post.teaser" class="mt-1.5 line-clamp-2 text-[13px] text-muted-foreground">{{ post.teaser }}</p>
<p class="mt-auto pt-3 text-xs text-muted-foreground">{{ formatShortDate(post.published_at) }} · {{ post.reading_minutes }} Min.</p>
</div>
</Link>
</template>

View file

@ -0,0 +1,17 @@
<script setup>
import { Newspaper } from '@lucide/vue';
defineProps({
src: { type: String, default: null },
alt: { type: String, default: '' },
});
</script>
<template>
<div class="relative aspect-video overflow-hidden bg-muted">
<img v-if="src" :src="src" :alt="alt" loading="lazy" class="size-full object-cover" />
<div v-else class="grid size-full place-items-center bg-brand-soft">
<Newspaper class="size-1/4 max-h-10 max-w-10 text-brand-text opacity-60" :stroke-width="1.5" />
</div>
</div>
</template>

View file

@ -0,0 +1,21 @@
<script setup>
import { Link } from '@inertiajs/vue3';
import CategoryLabel from './CategoryLabel.vue';
import NewsImage from './NewsImage.vue';
import { formatRelative } from '@/lib/format';
defineProps({
post: { type: Object, required: true },
});
</script>
<template>
<Link :href="`/neuigkeiten/${post.slug}`" class="group flex gap-4 py-3">
<NewsImage :src="post.thumb_url" :alt="post.title" class="w-28 shrink-0 rounded-md sm:w-32" />
<div class="min-w-0">
<CategoryLabel :category="post.category" />
<h3 class="mt-0.5 line-clamp-2 text-sm leading-snug font-semibold group-hover:underline">{{ post.title }}</h3>
<p class="mt-1 text-xs text-muted-foreground">{{ formatRelative(post.published_at) }}</p>
</div>
</Link>
</template>

View file

@ -0,0 +1,59 @@
<script setup>
import { Link, router } from '@inertiajs/vue3';
import { ChevronLeft, ChevronRight, Newspaper } from '@lucide/vue';
import { Button } from '@/components/ui/button';
import EmptyState from '@/components/EmptyState.vue';
import NewsCard from '../components/NewsCard.vue';
import AppLayout from '@/layouts/AppLayout.vue';
defineProps({
posts: { type: Object, required: true },
categories: { type: Array, required: true },
activeCategory: { type: String, default: null },
});
</script>
<template>
<AppLayout title="Neuigkeiten">
<div class="mb-6">
<h1 class="text-2xl font-semibold tracking-tight">Neuigkeiten</h1>
<p class="mt-1 text-sm text-muted-foreground">Aktuelles aus dem Unternehmen und den Bereichen.</p>
</div>
<nav v-if="categories.length" class="mb-6 flex flex-wrap gap-2" aria-label="Kategorien">
<Link
href="/neuigkeiten"
class="rounded-full border px-3.5 py-1.5 text-[13px] font-medium transition-colors"
:class="!activeCategory ? 'border-brand bg-brand text-brand-foreground' : 'bg-card hover:bg-accent'"
preserve-scroll
>
Alle
</Link>
<Link
v-for="category in categories"
:key="category.slug"
:href="`/neuigkeiten?kategorie=${category.slug}`"
class="rounded-full border px-3.5 py-1.5 text-[13px] font-medium transition-colors"
:class="activeCategory === category.slug ? 'border-brand bg-brand text-brand-foreground' : 'bg-card hover:bg-accent'"
preserve-scroll
>
{{ category.name }}
</Link>
</nav>
<div v-if="posts.data.length" class="grid gap-5 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4">
<NewsCard v-for="post in posts.data" :key="post.id" :post="post" />
</div>
<div v-else class="rounded-lg border border-dashed bg-card">
<EmptyState :icon="Newspaper" title="Keine Beiträge" text="In dieser Kategorie ist noch nichts veröffentlicht." />
</div>
<nav v-if="posts.meta.last_page > 1" class="mt-8 flex items-center justify-between" aria-label="Seiten">
<p class="text-sm text-muted-foreground">Seite {{ posts.meta.current_page }} von {{ posts.meta.last_page }}</p>
<div class="flex gap-2">
<Button variant="outline" size="sm" :disabled="!posts.links.prev" @click="router.get(posts.links.prev)"><ChevronLeft /> Neuere</Button>
<Button variant="outline" size="sm" :disabled="!posts.links.next" @click="router.get(posts.links.next)">Ältere <ChevronRight /></Button>
</div>
</nav>
</AppLayout>
</template>

View file

@ -0,0 +1,53 @@
<script setup>
import { Link } from '@inertiajs/vue3';
import { ArrowLeft, Clock } from '@lucide/vue';
import CategoryLabel from '../components/CategoryLabel.vue';
import NewsCard from '../components/NewsCard.vue';
import PersonAvatar from '@/components/PersonAvatar.vue';
import AppLayout from '@/layouts/AppLayout.vue';
import { formatDate } from '@/lib/format';
defineProps({
post: { type: Object, required: true },
related: { type: Object, required: true },
});
</script>
<template>
<AppLayout :title="post.title">
<article class="mx-auto max-w-3xl">
<Link href="/neuigkeiten" class="mb-6 inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground">
<ArrowLeft class="size-4" /> Alle Neuigkeiten
</Link>
<header>
<CategoryLabel :category="post.category" />
<h1 class="mt-2 text-3xl leading-tight font-semibold tracking-tight sm:text-[34px]">{{ post.title }}</h1>
<p v-if="post.teaser" class="mt-4 text-lg leading-relaxed text-muted-foreground">{{ post.teaser }}</p>
<div class="mt-6 flex flex-wrap items-center gap-x-6 gap-y-3 border-y py-4 text-sm">
<Link v-if="post.author" :href="`/personen/${post.author.id}`" class="flex items-center gap-3 hover:underline">
<PersonAvatar :person="post.author" class="size-9" />
<span>
<span class="block font-medium">{{ post.author.name }}</span>
<span v-if="post.author.job_title" class="block text-xs text-muted-foreground">{{ post.author.job_title }}</span>
</span>
</Link>
<span class="text-muted-foreground">{{ formatDate(post.published_at) }}</span>
<span class="inline-flex items-center gap-1.5 text-muted-foreground"><Clock class="size-4" /> {{ post.reading_minutes }} Min. Lesezeit</span>
</div>
</header>
<img v-if="post.cover_url" :src="post.cover_url" :alt="post.title" class="mt-8 aspect-video w-full rounded-lg object-cover" />
<div class="prose prose-neutral mt-8 max-w-none prose-headings:tracking-tight prose-img:rounded-lg" v-html="post.body_html" />
</article>
<section v-if="related.data.length" class="mx-auto mt-16 max-w-5xl">
<h2 class="mb-4 text-lg font-semibold">Weitere Beiträge</h2>
<div class="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
<NewsCard v-for="item in related.data" :key="item.id" :post="item" />
</div>
</section>
</AppLayout>
</template>

View file

@ -0,0 +1,17 @@
<script setup>
import Panel from '@/components/Panel.vue';
import NewsCard from '../components/NewsCard.vue';
defineProps({
posts: { type: Array, required: true },
});
</script>
<template>
<Panel title="Aktuelles aus den Bereichen" action-label="Alle" action-href="/neuigkeiten">
<!-- Mobil wischbar, ab sm als Raster -->
<div class="-mx-5 flex snap-x scroll-px-5 gap-4 overflow-x-auto px-5 pb-1 [scrollbar-width:none] sm:mx-0 sm:grid sm:grid-cols-2 sm:overflow-visible sm:px-0 sm:pb-0 xl:grid-cols-4 [&::-webkit-scrollbar]:hidden">
<NewsCard v-for="post in posts" :key="post.id" :post="post" class="w-[78%] shrink-0 snap-start sm:w-auto" />
</div>
</Panel>
</template>

View file

@ -0,0 +1,11 @@
<script setup>
import HeroSlider from '../components/HeroSlider.vue';
defineProps({
posts: { type: Array, required: true },
});
</script>
<template>
<HeroSlider :posts="posts" class="h-full" />
</template>

View file

@ -0,0 +1,23 @@
<script setup>
import { Newspaper } from '@lucide/vue';
import EmptyState from '@/components/EmptyState.vue';
import Panel from '@/components/Panel.vue';
import NewsListItem from '../components/NewsListItem.vue';
defineProps({
posts: { type: Array, required: true },
canWrite: { type: Boolean, default: false },
wide: { type: Boolean, default: false },
});
</script>
<template>
<Panel title="Neuigkeiten" action-label="Alle anzeigen" action-href="/neuigkeiten">
<div v-if="posts.length" class="-my-3 divide-y" :class="{ 'sm:grid sm:grid-cols-2 sm:gap-x-6 sm:divide-y-0': wide }">
<NewsListItem v-for="post in posts" :key="post.id" :post="post" />
</div>
<EmptyState v-else :icon="Newspaper" title="Noch keine Neuigkeiten" text="Sobald Beiträge veröffentlicht sind, erscheinen sie hier.">
<a v-if="canWrite" href="/admin/neuigkeiten/neu" class="mt-4 text-sm font-medium text-brand-text hover:underline">Ersten Beitrag schreiben</a>
</EmptyState>
</Panel>
</template>

View file

@ -0,0 +1,9 @@
<?php
use Illuminate\Support\Facades\Route;
use Inhaus\Plugins\News\Http\Controllers\NewsController;
Route::middleware('auth')->group(function () {
Route::get('/neuigkeiten', [NewsController::class, 'index'])->name('news.index');
Route::get('/neuigkeiten/{post:slug}', [NewsController::class, 'show'])->name('news.show');
});

View file

@ -0,0 +1,26 @@
<?php
namespace Inhaus\Plugins\News\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use Inhaus\Plugins\News\Models\NewsCategory;
/**
* @extends Factory<NewsCategory>
*/
class NewsCategoryFactory extends Factory
{
protected $model = NewsCategory::class;
public function definition(): array
{
$name = fake()->unique()->words(2, true);
return [
'name' => Str::title($name),
'slug' => Str::slug($name),
'sort' => 0,
];
}
}

View file

@ -0,0 +1,34 @@
<?php
namespace Inhaus\Plugins\News\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Inhaus\Plugins\News\Models\NewsPost;
/**
* @extends Factory<NewsPost>
*/
class NewsPostFactory extends Factory
{
protected $model = NewsPost::class;
public function definition(): array
{
return [
'title' => fake()->sentence(6),
'teaser' => fake()->sentence(15),
'body' => '<p>'.fake()->paragraph(5).'</p>',
'published_at' => now()->subDay(),
];
}
public function draft(): static
{
return $this->state(fn () => ['published_at' => null]);
}
public function scheduled(): static
{
return $this->state(fn () => ['published_at' => now()->addDay()]);
}
}

View file

@ -0,0 +1,78 @@
<?php
namespace Inhaus\Plugins\News\Filament\Resources\NewsCategories;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Str;
use Inhaus\Plugins\News\Filament\Resources\NewsCategories\Pages\ManageNewsCategories;
use Inhaus\Plugins\News\Models\NewsCategory;
use UnitEnum;
class NewsCategoryResource extends Resource
{
protected static ?string $model = NewsCategory::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedTag;
protected static string|UnitEnum|null $navigationGroup = 'Inhalte';
protected static ?int $navigationSort = 2;
protected static ?string $modelLabel = 'Kategorie';
protected static ?string $pluralModelLabel = 'Kategorien';
protected static ?string $slug = 'kategorien';
public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('name')
->label('Name')
->required()
->maxLength(60)
->live(onBlur: true)
->afterStateUpdated(fn (?string $state, Set $set, string $operation) => $operation === 'create' ? $set('slug', Str::slug((string) $state, language: 'de')) : null),
TextInput::make('slug')
->label('Kürzel in der Adresse')
->required()
->maxLength(80)
->alphaDash()
->unique(ignoreRecord: true),
TextInput::make('description')->label('Beschreibung')->maxLength(500)->columnSpanFull(),
TextInput::make('sort')->label('Reihenfolge')->numeric()->default(0),
]);
}
public static function table(Table $table): Table
{
return $table
->defaultSort('sort')
->reorderable('sort')
->columns([
TextColumn::make('name')->label('Name')->searchable(),
TextColumn::make('slug')->label('Kürzel')->color('gray'),
TextColumn::make('posts_count')->label('Beiträge')->counts('posts'),
])
->recordActions([
EditAction::make(),
DeleteAction::make(),
]);
}
public static function getPages(): array
{
return [
'index' => ManageNewsCategories::route('/'),
];
}
}

View file

@ -0,0 +1,19 @@
<?php
namespace Inhaus\Plugins\News\Filament\Resources\NewsCategories\Pages;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ManageRecords;
use Inhaus\Plugins\News\Filament\Resources\NewsCategories\NewsCategoryResource;
class ManageNewsCategories extends ManageRecords
{
protected static string $resource = NewsCategoryResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}

View file

@ -0,0 +1,156 @@
<?php
namespace Inhaus\Plugins\News\Filament\Resources\NewsPosts;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages\CreateNewsPost;
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages\EditNewsPost;
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages\ListNewsPosts;
use Inhaus\Plugins\News\Models\NewsPost;
use UnitEnum;
class NewsPostResource extends Resource
{
protected static ?string $model = NewsPost::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedNewspaper;
protected static string|UnitEnum|null $navigationGroup = 'Inhalte';
protected static ?int $navigationSort = 1;
protected static ?string $modelLabel = 'Beitrag';
protected static ?string $pluralModelLabel = 'Neuigkeiten';
protected static ?string $slug = 'neuigkeiten';
protected static ?string $recordTitleAttribute = 'title';
public static function form(Schema $schema): Schema
{
return $schema
->columns(3)
->components([
Section::make('Beitrag')
->columnSpan(2)
->schema([
TextInput::make('title')->label('Titel')->required()->maxLength(160),
Textarea::make('teaser')
->label('Kurztext')
->helperText('Erscheint in Listen und auf der Startseite. 1–2 Sätze.')
->rows(2)
->maxLength(300),
RichEditor::make('body')
->label('Text')
->toolbarButtons([
['bold', 'italic', 'underline', 'link'],
['h2', 'h3'],
['bulletList', 'orderedList', 'blockquote'],
['attachFiles', 'table'],
['undo', 'redo'],
])
->fileAttachmentsDisk('uploads')
->fileAttachmentsDirectory('news/inline')
->fileAttachmentsVisibility('public')
->fileAttachmentsAcceptedFileTypes(['image/jpeg', 'image/png', 'image/webp'])
->fileAttachmentsMaxSize(8 * 1024),
]),
Section::make('Veröffentlichung')
->columnSpan(1)
->schema([
Select::make('category_id')
->label('Kategorie')
->relationship('category', 'name')
->preload()
->searchable(),
DateTimePicker::make('published_at')
->label('Veröffentlichen am')
->helperText('Leer lassen = Entwurf. Ein Datum in der Zukunft plant den Beitrag.')
->seconds(false)
->native(false)
->displayFormat('d.m.Y H:i'),
Toggle::make('is_featured')
->label('Auf der Startseite hervorheben')
->helperText('Hervorgehobene Beiträge mit Titelbild erscheinen groß im Slider.'),
FileUpload::make('cover_path')
->label('Titelbild')
->helperText('Querformat, mindestens 1600 × 900 Pixel.')
->image()
->disk('uploads')
->directory('news')
->visibility('public')
->imageAspectRatio('16:9')
->automaticallyCropImagesToAspectRatio()
->maxSize(10 * 1024),
]),
]);
}
public static function table(Table $table): Table
{
return $table
->defaultSort('created_at', 'desc')
->columns([
ImageColumn::make('cover_path')->label('')->disk('uploads')->width(80)->height(45),
TextColumn::make('title')->label('Titel')->searchable()->limit(60)->weight('medium'),
TextColumn::make('category.name')->label('Kategorie')->badge()->color('gray'),
TextColumn::make('status')
->label('Status')
->badge()
->state(fn (NewsPost $record) => match (true) {
$record->published_at === null => 'Entwurf',
$record->published_at->isFuture() => 'Geplant',
default => 'Veröffentlicht',
})
->color(fn (string $state) => match ($state) {
'Veröffentlicht' => 'success',
'Geplant' => 'warning',
default => 'gray',
}),
IconColumn::make('is_featured')->label('Hervorgehoben')->boolean()->trueIcon(Heroicon::Star)->falseIcon(false)->trueColor('warning'),
TextColumn::make('published_at')->label('Veröffentlicht')->dateTime('d.m.Y H:i')->sortable(),
])
->filters([
SelectFilter::make('category_id')->label('Kategorie')->relationship('category', 'name'),
])
->recordActions([
Action::make('view')
->label('Ansehen')
->icon(Heroicon::OutlinedEye)
->url(fn (NewsPost $record) => route('news.show', $record))
->openUrlInNewTab()
->visible(fn (NewsPost $record) => $record->isPublished()),
EditAction::make(),
DeleteAction::make(),
]);
}
public static function getPages(): array
{
return [
'index' => ListNewsPosts::route('/'),
'create' => CreateNewsPost::route('/neu'),
'edit' => EditNewsPost::route('/{record}/bearbeiten'),
];
}
}

View file

@ -0,0 +1,18 @@
<?php
namespace Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages;
use Filament\Resources\Pages\CreateRecord;
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\NewsPostResource;
class CreateNewsPost extends CreateRecord
{
protected static string $resource = NewsPostResource::class;
protected function mutateFormDataBeforeCreate(array $data): array
{
$data['author_id'] = auth()->id();
return $data;
}
}

View file

@ -0,0 +1,19 @@
<?php
namespace Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\NewsPostResource;
class EditNewsPost extends EditRecord
{
protected static string $resource = NewsPostResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
}

View file

@ -0,0 +1,19 @@
<?php
namespace Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\NewsPostResource;
class ListNewsPosts extends ListRecords
{
protected static string $resource = NewsPostResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()->label('Neuer Beitrag'),
];
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace Inhaus\Plugins\News\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\News\Http\Resources\NewsPostResource;
use Inhaus\Plugins\News\Models\NewsCategory;
use Inhaus\Plugins\News\Models\NewsPost;
class NewsController extends Controller
{
public function index(Request $request): Response
{
$categories = NewsCategory::query()->orderBy('sort')->orderBy('name')->get(['id', 'name', 'slug']);
$category = $categories->firstWhere('slug', $request->query('kategorie'));
$posts = NewsPost::query()
->published()
->with('category')
->when($category, fn ($query) => $query->where('category_id', $category->id))
->latest('published_at')
->paginate(12)
->withQueryString();
return Inertia::render('news::Index', [
'posts' => NewsPostResource::collection($posts),
'categories' => $categories->map(fn (NewsCategory $c) => ['name' => $c->name, 'slug' => $c->slug]),
'activeCategory' => $category?->slug,
]);
}
public function show(NewsPost $post): Response
{
abort_unless($post->isPublished(), 404);
$post->load(['category', 'author']);
return Inertia::render('news::Show', [
'post' => [
...(new NewsPostResource($post))->resolve(),
'body_html' => $post->body_html,
'author' => $post->author ? [
'id' => $post->author->id,
'name' => $post->author->name,
'initials' => $post->author->initials,
'job_title' => $post->author->job_title,
'avatar_url' => $post->author->avatarUrl(96),
] : null,
],
'related' => NewsPostResource::collection(
NewsPost::query()
->published()
->with('category')
->whereKeyNot($post->id)
->when($post->category_id, fn ($query) => $query->where('category_id', $post->category_id))
->latest('published_at')
->limit(3)
->get()
),
]);
}
}

View file

@ -0,0 +1,34 @@
<?php
namespace Inhaus\Plugins\News\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Inhaus\Plugins\News\Models\NewsPost;
/**
* @mixin NewsPost
*/
class NewsPostResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'teaser' => $this->teaser,
'category' => $this->whenLoaded('category', fn () => $this->category ? [
'name' => $this->category->name,
'slug' => $this->category->slug,
] : null),
'cover_url' => $this->coverUrl('large'),
'thumb_url' => $this->coverUrl('thumb'),
'published_at' => $this->published_at?->toIso8601String(),
'reading_minutes' => $this->reading_minutes,
];
}
}

View file

@ -0,0 +1,28 @@
<?php
namespace Inhaus\Plugins\News\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Inhaus\Plugins\News\Database\Factories\NewsCategoryFactory;
#[Fillable(['name', 'slug', 'description', 'sort'])]
class NewsCategory extends Model
{
use HasFactory;
protected static function newFactory(): NewsCategoryFactory
{
return NewsCategoryFactory::new();
}
/**
* @return HasMany<NewsPost, $this>
*/
public function posts(): HasMany
{
return $this->hasMany(NewsPost::class, 'category_id');
}
}

View file

@ -0,0 +1,125 @@
<?php
namespace Inhaus\Plugins\News\Models;
use App\Models\User;
use App\Support\Images;
use App\Support\RichText;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;
use Inhaus\Plugins\News\Database\Factories\NewsPostFactory;
#[Fillable([
'category_id', 'author_id', 'title', 'slug', 'teaser', 'body',
'cover_path', 'is_featured', 'published_at',
])]
class NewsPost extends Model
{
use HasFactory;
protected static function newFactory(): NewsPostFactory
{
return NewsPostFactory::new();
}
protected static function booted(): void
{
static::saving(function (NewsPost $post): void {
if (blank($post->slug)) {
$post->slug = static::uniqueSlug($post->title, $post->getKey());
}
if ($post->isDirty('body') || $post->body_html === null) {
$richText = app(RichText::class);
$post->body_html = $richText->toSafeHtml($post->body);
$post->reading_minutes = $richText->readingMinutes($post->body_html);
}
});
// Bildvarianten erzeugen bzw. beim Austausch die alten Dateien entfernen.
static::saved(function (NewsPost $post): void {
if (! $post->wasRecentlyCreated && ! $post->wasChanged('cover_path')) {
return;
}
$previous = $post->wasRecentlyCreated ? null : $post->getOriginal('cover_path');
if ($previous && $previous !== $post->cover_path) {
app(Images::class)->deleteWithVariants($previous);
}
if ($post->cover_path) {
app(Images::class)->createVariants($post->cover_path);
}
});
static::deleted(fn (NewsPost $post) => app(Images::class)->deleteWithVariants($post->cover_path));
}
protected function casts(): array
{
return [
'is_featured' => 'boolean',
'published_at' => 'datetime',
];
}
/**
* @return BelongsTo<NewsCategory, $this>
*/
public function category(): BelongsTo
{
return $this->belongsTo(NewsCategory::class);
}
/**
* @return BelongsTo<User, $this>
*/
public function author(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* Veröffentlicht = Veröffentlichungsdatum gesetzt und erreicht.
*
* @param Builder<NewsPost> $query
*/
public function scopePublished(Builder $query): void
{
$query->whereNotNull('published_at')->where('published_at', '<=', now());
}
public function isPublished(): bool
{
return $this->published_at !== null && $this->published_at->isPast();
}
public function coverUrl(string $variant = 'large'): ?string
{
return app(Images::class)->url($this->cover_path, $variant);
}
public static function uniqueSlug(string $title, ?int $ignoreId = null): string
{
$base = Str::slug($title, language: 'de') ?: 'beitrag';
$slug = $base;
for ($i = 2; static::query()->where('slug', $slug)->when($ignoreId, fn ($q) => $q->whereKeyNot($ignoreId))->exists(); $i++) {
$slug = "{$base}-{$i}";
}
return $slug;
}
/**
* Nur Einträge, die diese Person sehen darf (Zielgruppen). Platzhalter bis Phase 2c.
*
* @param Builder<NewsPost> $query
*/
public function scopeVisibleTo(Builder $query, ?User $user): void {}
}

View file

@ -0,0 +1,76 @@
<?php
namespace Inhaus\Plugins\News;
use App\Dashboard\Widgets;
use App\Models\User;
use App\Plugins\Plugin;
use App\Support\Abilities;
use App\Support\Navigation;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Inhaus\Plugins\News\Http\Resources\NewsPostResource;
use Inhaus\Plugins\News\Models\NewsCategory;
use Inhaus\Plugins\News\Models\NewsPost;
class NewsPlugin extends Plugin
{
public function register(): void
{
$this->app->make(Navigation::class)->add('news', 'Neuigkeiten', '/neuigkeiten', active: 'news.*', sort: 20);
$abilities = $this->app->make(Abilities::class);
$abilities->define('news.manage', 'Neuigkeiten: alle Kategorien verwalten', 'Neuigkeiten');
$abilities->define('news.post.create', 'Beiträge schreiben', 'Neuigkeiten', resource: 'news_category');
$abilities->define('news.post.publish', 'Beiträge veröffentlichen', 'Neuigkeiten', resource: 'news_category');
$abilities->resourceType('news_category', 'Kategorie', fn () => NewsCategory::query()->orderBy('sort')->pluck('name', 'id')->all());
$this->registerWidgets($this->app->make(Widgets::class));
}
private function registerWidgets(Widgets $widgets): void
{
// Slider: hervorgehobene Beiträge mit Bild, sonst die neuesten mit Bild.
$widgets->add('news.hero', 'news::Hero', 'hero', sort: 10, props: function (User $user) {
$featured = $this->featured($user);
return $featured->isEmpty() ? null : ['posts' => NewsPostResource::collection($featured)->resolve()];
}, mobileSort: 10);
$widgets->add('news.latest', 'news::Latest', 'feed', sort: 10, props: function (User $user, Request $request) {
$posts = NewsPost::query()->published()->visibleTo($user)->with('category')
->whereKeyNot($this->featured($user)->modelKeys())
->latest('published_at')->limit(4)->get();
return [
'posts' => NewsPostResource::collection($posts)->resolve(),
'canWrite' => $user->can('news.manage'),
];
}, mobileSort: 20);
$widgets->add('news.areas', 'news::Areas', 'main', sort: 20, props: function (User $user) {
$posts = NewsPost::query()->published()->visibleTo($user)->with('category')
->whereKeyNot($this->featured($user)->modelKeys())
->latest('published_at')->skip(4)->limit(4)->get();
return $posts->isEmpty() ? null : ['posts' => NewsPostResource::collection($posts)->resolve()];
}, mobileSort: 50);
}
/**
* @return Collection<int, NewsPost>
*/
private function featured(User $user)
{
static $cache = [];
return $cache[$user->id] ??= (function () use ($user) {
$featured = NewsPost::query()->published()->visibleTo($user)->with('category')
->where('is_featured', true)->whereNotNull('cover_path')
->latest('published_at')->limit(5)->get();
return $featured->isNotEmpty() ? $featured : NewsPost::query()->published()->visibleTo($user)->with('category')
->whereNotNull('cover_path')->latest('published_at')->limit(3)->get();
})();
}
}