Phase 4: Seiten mit Pagebuilder, Redaktion und Freigaben
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m56s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m56s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m2s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m9s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 2m40s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 2m35s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 2m29s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 2m38s
CI / Build-Artefakte aktuell (pull_request) Successful in 55s
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m56s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m56s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m2s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m9s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 2m40s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 2m35s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 2m29s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 2m38s
CI / Build-Artefakte aktuell (pull_request) Successful in 55s
- Seiten-Plugin: Seitenbaum mit Adressen, Seitennavigation, Brotkrumen und optional Hauptnavigation; Sichtbarkeit vererbt sich auf Unterseiten - Pagebuilder (Block-Registry im Kern, Plugins tragen Blöcke bei): Abschnitt, Spalten, Tabs, Akkordeon, Box, Überschrift, Text (TipTap), Zitat, Schaltflächen, Symbolliste, Tabelle, Trennlinie, Abstand, Bild, Galerie, Video (erst nach Klick), Titelbild, Ansprechpartner, Downloads, Unterseiten, Neuigkeiten, Termine; Sichtbarkeit je Block; Bereinigung beim Speichern - Editor im Portal: Ziehen und Ablegen, Autospeichern als Entwurf, Rückgängig, Gerätevorschau, Versionen, Zeitsteuerung, Bearbeitungssperre, Freigabe anfordern - Rechte „inkl. Unterseiten“ werden im Rechte-Cache aufgelöst - Neuigkeiten: Schreiben im Portal, Freigabe-Workflow mit Benachrichtigungen - Bereich „Redaktion“, Benachrichtigungen im Portal - storage/.migrations-fingerprint nicht mehr ausliefern Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
6269d3302c
commit
f3987e8386
328 changed files with 10618 additions and 389 deletions
|
|
@ -1,13 +1,13 @@
|
|||
{
|
||||
"slug": "events",
|
||||
"name": "Termine",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"description": "Veranstaltungen und Fortbildungen mit Kalender-Export.",
|
||||
"author": "Inhaus",
|
||||
"namespace": "Inhaus\\Plugins\\Events\\",
|
||||
"class": "Inhaus\\Plugins\\Events\\EventsPlugin",
|
||||
"requires": {
|
||||
"core": ">=0.3.0",
|
||||
"core": ">=0.5.0",
|
||||
"php": ">=8.3"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
20
plugins-core/events/resources/js/blocks/UpcomingEvents.vue
Normal file
20
plugins-core/events/resources/js/blocks/UpcomingEvents.vue
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { ChevronRight } from '@lucide/vue';
|
||||
import EventListItem from '../components/EventListItem.vue';
|
||||
|
||||
defineProps({ block: { type: Object, required: true } });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section>
|
||||
<div v-if="block.data.title" class="mb-3 flex items-center justify-between gap-4">
|
||||
<h3 class="text-lg font-semibold">{{ block.data.title }}</h3>
|
||||
<Link href="/termine" class="inline-flex items-center gap-0.5 text-[13px] font-medium text-brand-text hover:underline">Alle Termine <ChevronRight class="size-3.5" /></Link>
|
||||
</div>
|
||||
<div class="divide-y rounded-lg border bg-card px-4">
|
||||
<EventListItem v-for="event in block.props?.events ?? []" :key="event.id" :event="event" />
|
||||
<p v-if="!(block.props?.events ?? []).length" class="py-3 text-sm text-muted-foreground">Keine anstehenden Termine.</p>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -4,6 +4,9 @@ namespace Inhaus\Plugins\Events;
|
|||
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Blocks;
|
||||
use App\Pagebuilder\BlockType;
|
||||
use App\Pagebuilder\Field;
|
||||
use App\Plugins\Plugin;
|
||||
use App\Support\Abilities;
|
||||
use App\Support\Navigation;
|
||||
|
|
@ -23,5 +26,15 @@ class EventsPlugin extends Plugin
|
|||
$this->app->make(Widgets::class)->add('events.upcoming', 'events::Upcoming', 'aside', sort: 20, props: fn (User $user) => [
|
||||
'events' => EventResource::collection(Event::query()->upcoming()->visibleTo($user)->limit(4)->get())->resolve(),
|
||||
], mobileSort: 30);
|
||||
|
||||
$this->app->make(Blocks::class)->add(BlockType::make('events.upcoming', 'Termine', 'calendar-days', 'dynamic', 'events::UpcomingEvents')
|
||||
->description('Die nächsten Termine.')
|
||||
->fields([
|
||||
Field::text('title', 'Überschrift', 150, 'Termine'),
|
||||
Field::number('count', 'Anzahl', 1, 12, 4),
|
||||
])
|
||||
->resolveUsing(fn (array $data, ?User $user) => [
|
||||
'events' => EventResource::collection(Event::query()->upcoming()->visibleTo($user)->limit($data['count'])->get())->resolve(),
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,35 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Freigabe-Workflow: Entwurf → zur Freigabe → veröffentlicht (ggf. geplant).
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('news_posts', function (Blueprint $table) {
|
||||
$table->string('status', 20)->default('draft')->after('is_featured');
|
||||
$table->timestamp('submitted_at')->nullable()->after('status');
|
||||
$table->foreignId('reviewed_by')->nullable()->after('submitted_at')->constrained('users')->nullOnDelete();
|
||||
$table->text('review_note')->nullable()->after('reviewed_by');
|
||||
|
||||
$table->index(['status', 'category_id']);
|
||||
});
|
||||
|
||||
DB::table('news_posts')->whereNotNull('published_at')->update(['status' => 'published']);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('news_posts', function (Blueprint $table) {
|
||||
$table->dropIndex(['status', 'category_id']);
|
||||
$table->dropConstrainedForeignId('reviewed_by');
|
||||
$table->dropColumn(['status', 'submitted_at', 'review_note']);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -1,13 +1,13 @@
|
|||
{
|
||||
"slug": "news",
|
||||
"name": "Neuigkeiten",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.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",
|
||||
"core": ">=0.5.0",
|
||||
"php": ">=8.3"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
26
plugins-core/news/resources/js/blocks/LatestNews.vue
Normal file
26
plugins-core/news/resources/js/blocks/LatestNews.vue
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { ChevronRight } from '@lucide/vue';
|
||||
import NewsCard from '../components/NewsCard.vue';
|
||||
import NewsListItem from '../components/NewsListItem.vue';
|
||||
|
||||
defineProps({ block: { type: Object, required: true } });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section>
|
||||
<div v-if="block.data.title" class="mb-3 flex items-center justify-between gap-4">
|
||||
<h3 class="text-lg font-semibold">{{ block.data.title }}</h3>
|
||||
<Link v-if="block.props?.more_url" :href="block.props.more_url" class="inline-flex items-center gap-0.5 text-[13px] font-medium text-brand-text hover:underline">
|
||||
Alle anzeigen <ChevronRight class="size-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
<div v-if="block.data.layout === 'list'" class="divide-y rounded-lg border bg-card px-4">
|
||||
<NewsListItem v-for="post in block.props?.posts ?? []" :key="post.id" :post="post" />
|
||||
</div>
|
||||
<div v-else class="grid gap-5 @xl:grid-cols-2 @4xl:grid-cols-3">
|
||||
<NewsCard v-for="post in block.props?.posts ?? []" :key="post.id" :post="post" />
|
||||
</div>
|
||||
<p v-if="!(block.props?.posts ?? []).length" class="text-sm text-muted-foreground">Keine Beiträge.</p>
|
||||
</section>
|
||||
</template>
|
||||
55
plugins-core/news/resources/js/editorial/EditorialNews.vue
Normal file
55
plugins-core/news/resources/js/editorial/EditorialNews.vue
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { MessageSquareWarning, Plus } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import { formatRelative } from '@/lib/format';
|
||||
|
||||
defineProps({
|
||||
review: { type: Array, required: true },
|
||||
mine: { type: Array, required: true },
|
||||
scheduled: { type: Array, required: true },
|
||||
canCreate: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const badge = (post) => ({
|
||||
pending: 'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-200',
|
||||
published: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-200',
|
||||
draft: 'bg-muted text-muted-foreground',
|
||||
})[post.status];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Panel title="Neuigkeiten">
|
||||
<template #actions>
|
||||
<Button v-if="canCreate" size="sm" as-child><Link href="/redaktion/neuigkeiten/neu"><Plus /> Neuer Beitrag</Link></Button>
|
||||
</template>
|
||||
|
||||
<div class="grid gap-5">
|
||||
<section v-for="group in [
|
||||
{ key: 'review', title: 'Zur Freigabe', items: review, empty: null },
|
||||
{ key: 'mine', title: 'Meine Entwürfe', items: mine, empty: 'Keine offenen Entwürfe.' },
|
||||
{ key: 'scheduled', title: 'Geplant', items: scheduled, empty: null },
|
||||
].filter((g) => g.items.length || g.empty)" :key="group.key">
|
||||
<h3 class="mb-1 text-xs font-semibold tracking-wide text-muted-foreground uppercase">
|
||||
{{ group.title }}
|
||||
<span v-if="group.key === 'review'" class="ml-1 rounded-full bg-brand px-1.5 py-0.5 text-[10px] text-brand-foreground">{{ group.items.length }}</span>
|
||||
</h3>
|
||||
<ul v-if="group.items.length" class="-mx-5 divide-y border-y">
|
||||
<li v-for="post in group.items" :key="post.id" class="flex items-center gap-3 px-5 py-2.5">
|
||||
<div class="min-w-0 flex-1">
|
||||
<Link :href="post.edit_url" class="block truncate text-sm font-medium hover:underline">{{ post.title }}</Link>
|
||||
<p class="truncate text-xs text-muted-foreground">
|
||||
{{ post.category ?? 'Ohne Kategorie' }}<template v-if="group.key !== 'mine' && post.author"> · {{ post.author }}</template>
|
||||
<template v-if="post.date"> · {{ formatRelative(post.date) }}</template>
|
||||
</p>
|
||||
</div>
|
||||
<MessageSquareWarning v-if="post.review_note" class="size-4 shrink-0 text-amber-600" title="Mit Anmerkung zurückgegeben" />
|
||||
<span class="shrink-0 rounded px-1.5 py-0.5 text-[11px] font-medium" :class="badge(post)">{{ post.status_label }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="text-sm text-muted-foreground">{{ group.empty }}</p>
|
||||
</section>
|
||||
</div>
|
||||
</Panel>
|
||||
</template>
|
||||
239
plugins-core/news/resources/js/pages/Editor.vue
Normal file
239
plugins-core/news/resources/js/pages/Editor.vue
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
<script setup>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { Link, router, useForm, usePage } from '@inertiajs/vue3';
|
||||
import { ArrowLeft, CalendarClock, Eye, ImagePlus, LoaderCircle, MessageSquareWarning, Save, Send, Trash2, Undo2, X } from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import FormField from '@/components/FormField.vue';
|
||||
import NativeSelect from '@/components/NativeSelect.vue';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import RichTextEditor from '@/components/RichTextEditor.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import { http } from '@/lib/http';
|
||||
|
||||
const props = defineProps({
|
||||
post: { type: Object, default: null },
|
||||
categories: { type: Array, required: true },
|
||||
canPublishWithoutCategory: { type: Boolean, default: false },
|
||||
canDelete: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const page = usePage();
|
||||
|
||||
function localValue(iso) {
|
||||
if (!iso) return '';
|
||||
const date = new Date(iso);
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
||||
}
|
||||
|
||||
const form = useForm({
|
||||
title: props.post?.title ?? '',
|
||||
teaser: props.post?.teaser ?? '',
|
||||
body: props.post?.body ?? '',
|
||||
category_id: props.post?.category_id ?? (props.categories.length === 1 ? props.categories[0].id : null),
|
||||
cover: null,
|
||||
remove_cover: false,
|
||||
is_featured: props.post?.is_featured ?? false,
|
||||
published_at: localValue(props.post?.published_at),
|
||||
action: 'draft',
|
||||
});
|
||||
|
||||
const category = computed(() => props.categories.find((c) => c.id === Number(form.category_id)));
|
||||
const canPublish = computed(() => (category.value ? category.value.can_publish : props.canPublishWithoutCategory));
|
||||
const isPending = computed(() => props.post?.status === 'pending');
|
||||
const isPublished = computed(() => props.post?.status === 'published');
|
||||
const categoryOptions = computed(() => props.categories.map((c) => ({ value: c.id, label: c.name })));
|
||||
|
||||
// Titelbild
|
||||
const coverPreview = ref(props.post?.cover_url ?? null);
|
||||
const coverInput = ref(null);
|
||||
|
||||
function chooseCover(event) {
|
||||
const file = event.target.files?.[0];
|
||||
|
||||
if (!file) return;
|
||||
|
||||
form.cover = file;
|
||||
form.remove_cover = false;
|
||||
coverPreview.value = URL.createObjectURL(file);
|
||||
}
|
||||
|
||||
function removeCover() {
|
||||
form.cover = null;
|
||||
form.remove_cover = true;
|
||||
coverPreview.value = null;
|
||||
}
|
||||
|
||||
async function uploadImage(file) {
|
||||
const body = new FormData();
|
||||
body.append('image', file);
|
||||
|
||||
try {
|
||||
return (await http.post('/redaktion/neuigkeiten/bilder', body)).url;
|
||||
} catch (error) {
|
||||
toast.error(error.fieldErrors?.image ?? error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function submit(action) {
|
||||
form.action = action;
|
||||
form.transform((data) => ({
|
||||
...data,
|
||||
published_at: data.published_at ? new Date(data.published_at).toISOString() : null,
|
||||
category_id: data.category_id ? Number(data.category_id) : null,
|
||||
...(props.post ? { _method: 'put' } : {}),
|
||||
})).post(props.post ? `/redaktion/neuigkeiten/${props.post.id}` : '/redaktion/neuigkeiten', {
|
||||
forceFormData: true,
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.cover = null;
|
||||
form.defaults();
|
||||
},
|
||||
onError: (errors) => errors.action && toast.error(errors.action),
|
||||
});
|
||||
}
|
||||
|
||||
watch(() => page.props.flash.status, (status) => status && toast.success(status), { immediate: true });
|
||||
|
||||
// Freigabe durch die Redaktion
|
||||
const rejecting = ref(false);
|
||||
const rejectForm = useForm({ note: '' });
|
||||
|
||||
function approve() {
|
||||
router.post(`/redaktion/neuigkeiten/${props.post.id}/freigeben`, { published_at: form.published_at ? new Date(form.published_at).toISOString() : null });
|
||||
}
|
||||
|
||||
function reject() {
|
||||
rejectForm.post(`/redaktion/neuigkeiten/${props.post.id}/zurueckgeben`, { onSuccess: () => (rejecting.value = false) });
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
if (window.confirm('Beitrag endgültig löschen?')) {
|
||||
router.delete(`/redaktion/neuigkeiten/${props.post.id}`);
|
||||
}
|
||||
}
|
||||
|
||||
const scheduled = computed(() => form.published_at && new Date(form.published_at) > new Date());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout :title="post ? `Bearbeiten: ${post.title}` : 'Neuer Beitrag'">
|
||||
<div class="mb-6 flex flex-wrap items-center justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<Link href="/redaktion" class="mb-2 inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground"><ArrowLeft class="size-4" /> Redaktion</Link>
|
||||
<h1 class="text-2xl font-semibold tracking-tight">{{ post ? 'Beitrag bearbeiten' : 'Neuer Beitrag' }}</h1>
|
||||
</div>
|
||||
<div v-if="post" class="flex items-center gap-2">
|
||||
<span class="rounded px-2 py-1 text-xs font-medium" :class="{
|
||||
'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-200': post.status === 'pending' || post.status_label === 'Geplant',
|
||||
'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-200': post.status_label === 'Veröffentlicht',
|
||||
'bg-muted text-muted-foreground': post.status === 'draft',
|
||||
}">{{ post.status_label }}</span>
|
||||
<Button v-if="post.url" variant="outline" size="sm" as-child><a :href="post.url"><Eye /> Ansehen</a></Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="post?.review_note" class="mb-6 flex gap-3 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-950 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-100">
|
||||
<MessageSquareWarning class="mt-0.5 size-4 shrink-0" />
|
||||
<div><p class="font-medium">Zurückgegeben mit Anmerkung</p><p class="mt-0.5 whitespace-pre-line">{{ post.review_note }}</p></div>
|
||||
</div>
|
||||
|
||||
<div v-if="isPending && canPublish" class="mb-6 flex flex-wrap items-center gap-3 rounded-lg border border-brand-200 bg-brand-soft px-4 py-3 text-sm">
|
||||
<p class="flex-1">{{ post.author }} hat diesen Beitrag zur Freigabe eingereicht.</p>
|
||||
<Button size="sm" variant="outline" class="bg-card" @click="rejecting = true"><Undo2 /> Zurückgeben</Button>
|
||||
<Button size="sm" @click="approve"><Send /> {{ scheduled ? 'Freigeben und planen' : 'Freigeben' }}</Button>
|
||||
</div>
|
||||
|
||||
<div class="grid items-start gap-6 lg:grid-cols-12">
|
||||
<Panel class="lg:col-span-8">
|
||||
<div class="grid gap-5">
|
||||
<FormField id="title" label="Titel" :error="form.errors.title">
|
||||
<Input id="title" v-model="form.title" maxlength="160" class="h-11 text-lg font-semibold" />
|
||||
</FormField>
|
||||
<FormField id="teaser" label="Kurztext" :error="form.errors.teaser" hint="Erscheint in Listen und auf der Startseite. 1–2 Sätze.">
|
||||
<Textarea id="teaser" v-model="form.teaser" rows="2" maxlength="300" />
|
||||
</FormField>
|
||||
<div class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Text</span>
|
||||
<RichTextEditor v-model="form.body" bordered :upload-image="uploadImage" placeholder="Beitrag schreiben …" min-height="[&_.tiptap]:min-h-72" />
|
||||
<p v-if="form.errors.body" class="text-[13px] text-destructive">{{ form.errors.body }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<div class="grid gap-6 lg:col-span-4">
|
||||
<Panel title="Veröffentlichung">
|
||||
<div class="grid gap-4">
|
||||
<FormField id="category" label="Kategorie" :error="form.errors.category_id">
|
||||
<NativeSelect id="category" v-model="form.category_id" :options="categoryOptions" :placeholder="canPublishWithoutCategory ? 'Ohne Kategorie' : 'Kategorie wählen …'" />
|
||||
</FormField>
|
||||
|
||||
<template v-if="canPublish">
|
||||
<FormField id="published_at" label="Veröffentlichen am" :error="form.errors.published_at" hint="Leer = sofort. Ein Datum in der Zukunft plant den Beitrag.">
|
||||
<Input id="published_at" v-model="form.published_at" type="datetime-local" />
|
||||
</FormField>
|
||||
<label class="flex items-center justify-between gap-3 text-[13px] font-medium">
|
||||
Auf der Startseite hervorheben
|
||||
<Switch v-model="form.is_featured" />
|
||||
</label>
|
||||
</template>
|
||||
<p v-else class="rounded-md bg-muted px-3 py-2 text-[13px] text-muted-foreground">
|
||||
In dieser Kategorie veröffentlicht die Redaktion. Reichen Sie den Beitrag zur Freigabe ein, wenn er fertig ist.
|
||||
</p>
|
||||
|
||||
<div class="grid gap-2 border-t pt-4">
|
||||
<Button v-if="canPublish" :disabled="form.processing || !form.title" @click="submit('publish')">
|
||||
<LoaderCircle v-if="form.processing && form.action === 'publish'" class="animate-spin" />
|
||||
<CalendarClock v-else-if="scheduled" /><Send v-else />
|
||||
{{ scheduled ? 'Planen' : isPublished ? 'Aktualisieren' : 'Veröffentlichen' }}
|
||||
</Button>
|
||||
<Button v-else :disabled="form.processing || !form.title || isPending" @click="submit('submit')">
|
||||
<Send /> {{ isPending ? 'Liegt zur Freigabe vor' : 'Zur Freigabe einreichen' }}
|
||||
</Button>
|
||||
<Button variant="outline" :disabled="form.processing || !form.title" @click="submit('draft')">
|
||||
<Save /> {{ isPublished ? 'Offline nehmen (Entwurf)' : 'Als Entwurf speichern' }}
|
||||
</Button>
|
||||
<Button v-if="canDelete" variant="ghost" class="text-destructive hover:text-destructive" @click="destroy"><Trash2 /> Löschen</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<Panel title="Titelbild">
|
||||
<div class="grid gap-3">
|
||||
<div v-if="coverPreview" class="relative overflow-hidden rounded-md border">
|
||||
<img :src="coverPreview" alt="" class="aspect-video w-full object-cover" />
|
||||
<button type="button" class="absolute top-2 right-2 grid size-8 place-items-center rounded-md bg-card/90 shadow-sm hover:bg-card" title="Titelbild entfernen" @click="removeCover"><X class="size-4" /></button>
|
||||
</div>
|
||||
<Button variant="outline" @click="coverInput?.click()"><ImagePlus /> {{ coverPreview ? 'Anderes Bild wählen' : 'Bild hochladen' }}</Button>
|
||||
<input ref="coverInput" type="file" accept="image/jpeg,image/png,image/webp" class="hidden" @change="chooseCover" />
|
||||
<p class="text-xs text-muted-foreground">Querformat, am besten 1600 × 900 Pixel. Wird auf 16:9 zugeschnitten.</p>
|
||||
<p v-if="form.errors.cover" class="text-[13px] text-destructive">{{ form.errors.cover }}</p>
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Dialog v-model:open="rejecting">
|
||||
<DialogContent class="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Beitrag zurückgeben</DialogTitle>
|
||||
<DialogDescription>{{ post?.author }} wird benachrichtigt und sieht Ihre Anmerkung.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<FormField id="note" label="Was soll geändert werden?" :error="rejectForm.errors.note">
|
||||
<Textarea id="note" v-model="rejectForm.note" rows="4" maxlength="1000" />
|
||||
</FormField>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="rejecting = false">Abbrechen</Button>
|
||||
<Button :disabled="rejectForm.processing || !rejectForm.note.trim()" @click="reject"><Undo2 /> Zurückgeben</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
<script setup>
|
||||
import { Link, router } from '@inertiajs/vue3';
|
||||
import { ChevronLeft, ChevronRight, Newspaper } from '@lucide/vue';
|
||||
import { ChevronLeft, ChevronRight, Newspaper, PenLine } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import EmptyState from '@/components/EmptyState.vue';
|
||||
import NewsCard from '../components/NewsCard.vue';
|
||||
|
|
@ -10,14 +10,18 @@ defineProps({
|
|||
posts: { type: Object, required: true },
|
||||
categories: { type: Array, required: true },
|
||||
activeCategory: { type: String, default: null },
|
||||
canWrite: { type: Boolean, default: false },
|
||||
});
|
||||
</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 class="mb-6 flex flex-wrap items-end justify-between gap-4">
|
||||
<div>
|
||||
<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>
|
||||
<Button v-if="canWrite" as-child><Link href="/redaktion/neuigkeiten/neu"><PenLine /> Beitrag schreiben</Link></Button>
|
||||
</div>
|
||||
|
||||
<nav v-if="categories.length" class="mb-6 flex flex-wrap gap-2" aria-label="Kategorien">
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { ArrowLeft, Clock } from '@lucide/vue';
|
||||
import { ArrowLeft, Clock, PenLine } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import CategoryLabel from '../components/CategoryLabel.vue';
|
||||
import NewsCard from '../components/NewsCard.vue';
|
||||
import PersonAvatar from '@/components/PersonAvatar.vue';
|
||||
|
|
@ -10,15 +11,19 @@ import { formatDate } from '@/lib/format';
|
|||
defineProps({
|
||||
post: { type: Object, required: true },
|
||||
related: { type: Object, required: true },
|
||||
editUrl: { type: String, default: null },
|
||||
});
|
||||
</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>
|
||||
<div class="mb-6 flex items-center justify-between gap-4">
|
||||
<Link href="/neuigkeiten" class="inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground">
|
||||
<ArrowLeft class="size-4" /> Alle Neuigkeiten
|
||||
</Link>
|
||||
<Button v-if="editUrl" variant="outline" size="sm" as-child><Link :href="editUrl"><PenLine /> Bearbeiten</Link></Button>
|
||||
</div>
|
||||
|
||||
<header>
|
||||
<CategoryLabel :category="post.category" />
|
||||
|
|
|
|||
|
|
@ -2,8 +2,20 @@
|
|||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Inhaus\Plugins\News\Http\Controllers\NewsController;
|
||||
use Inhaus\Plugins\News\Http\Controllers\NewsEditorController;
|
||||
|
||||
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');
|
||||
|
||||
Route::prefix('redaktion/neuigkeiten')->name('news.editor.')->controller(NewsEditorController::class)->group(function () {
|
||||
Route::get('/neu', 'create')->name('create');
|
||||
Route::post('/', 'store')->name('store');
|
||||
Route::post('/bilder', 'uploadImage')->name('images');
|
||||
Route::get('/{post}', 'edit')->name('edit');
|
||||
Route::put('/{post}', 'update')->name('update');
|
||||
Route::delete('/{post}', 'destroy')->name('destroy');
|
||||
Route::post('/{post}/freigeben', 'approve')->name('approve');
|
||||
Route::post('/{post}/zurueckgeben', 'reject')->name('reject');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
56
plugins-core/news/src/EditorialNews.php
Normal file
56
plugins-core/news/src/EditorialNews.php
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\News;
|
||||
|
||||
use App\Models\User;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
|
||||
/**
|
||||
* „Redaktion → Neuigkeiten“: eigene Entwürfe, Beiträge zur Freigabe und Geplantes.
|
||||
*/
|
||||
final class EditorialNews
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function props(User $user): array
|
||||
{
|
||||
$publishable = $user->can('news.manage') ? true : $user->permissions()->ids('news.post.publish', 'news_category');
|
||||
$writable = $user->can('news.manage') ? true : $user->permissions()->ids('news.post.create', 'news_category');
|
||||
|
||||
$map = fn (NewsPost $post) => [
|
||||
'id' => $post->id,
|
||||
'title' => $post->title,
|
||||
'category' => $post->category?->name,
|
||||
'author' => $post->author?->name,
|
||||
'status' => $post->status,
|
||||
'status_label' => $post->statusLabel(),
|
||||
'review_note' => $post->review_note,
|
||||
'date' => ($post->published_at ?? $post->submitted_at ?? $post->updated_at)?->toIso8601String(),
|
||||
'edit_url' => route('news.editor.edit', $post),
|
||||
];
|
||||
|
||||
$review = $publishable === [] ? collect() : NewsPost::query()->with(['category', 'author'])
|
||||
->where('status', NewsPost::PENDING)
|
||||
->when($publishable !== true, fn ($q) => $q->whereIn('category_id', $publishable))
|
||||
->oldest('submitted_at')->limit(20)->get();
|
||||
|
||||
$mine = NewsPost::query()->with(['category', 'author'])
|
||||
->where('author_id', $user->id)
|
||||
->where(fn ($q) => $q->whereIn('status', [NewsPost::DRAFT, NewsPost::PENDING])->orWhere('published_at', '>', now()))
|
||||
->latest('updated_at')->limit(20)->get();
|
||||
|
||||
$scheduled = NewsPost::query()->with(['category', 'author'])
|
||||
->where('status', NewsPost::PUBLISHED)->where('published_at', '>', now())
|
||||
->when($writable !== true, fn ($q) => $q->whereIn('category_id', $writable ?: [0]))
|
||||
->whereKeyNot($mine->modelKeys())
|
||||
->oldest('published_at')->limit(20)->get();
|
||||
|
||||
return [
|
||||
'review' => $review->map($map)->all(),
|
||||
'mine' => $mine->map($map)->all(),
|
||||
'scheduled' => $scheduled->map($map)->all(),
|
||||
'canCreate' => app(Policies\NewsPostPolicy::class)->create($user),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -158,14 +158,10 @@ class NewsPostResource extends Resource
|
|||
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',
|
||||
})
|
||||
->state(fn (NewsPost $record) => $record->statusLabel())
|
||||
->color(fn (string $state) => match ($state) {
|
||||
'Veröffentlicht' => 'success',
|
||||
'Geplant' => 'warning',
|
||||
'Geplant', 'Zur Freigabe' => 'warning',
|
||||
default => 'gray',
|
||||
}),
|
||||
IconColumn::make('is_featured')->label('Hervorgehoben')->boolean()->trueIcon(Heroicon::Star)->falseIcon(false)->trueColor('warning'),
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ class NewsController extends Controller
|
|||
'posts' => NewsPostResource::collection($posts),
|
||||
'categories' => $categories->map(fn (NewsCategory $c) => ['name' => $c->name, 'slug' => $c->slug]),
|
||||
'activeCategory' => $category?->slug,
|
||||
'canWrite' => $request->user()->can('create', NewsPost::class),
|
||||
]);
|
||||
}
|
||||
|
||||
|
|
@ -51,6 +52,7 @@ class NewsController extends Controller
|
|||
'avatar_url' => $post->author->avatarUrl(96),
|
||||
] : null,
|
||||
],
|
||||
'editUrl' => request()->user()->can('update', $post) ? route('news.editor.edit', $post) : null,
|
||||
'related' => NewsPostResource::collection(
|
||||
NewsPost::query()
|
||||
->published()
|
||||
|
|
|
|||
223
plugins-core/news/src/Http/Controllers/NewsEditorController.php
Normal file
223
plugins-core/news/src/Http/Controllers/NewsEditorController.php
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\News\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Support\Audit;
|
||||
use App\Support\Images;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\File;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Inhaus\Plugins\News\Models\NewsCategory;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
use Inhaus\Plugins\News\NewsWorkflow;
|
||||
use Inhaus\Plugins\News\Policies\NewsPostPolicy;
|
||||
|
||||
/**
|
||||
* Beiträge im Portal schreiben: speichern als Entwurf, zur Freigabe einreichen
|
||||
* oder – mit Veröffentlichungsrecht – direkt veröffentlichen bzw. planen.
|
||||
*/
|
||||
class NewsEditorController extends Controller
|
||||
{
|
||||
public function __construct(private readonly NewsWorkflow $workflow, private readonly NewsPostPolicy $policy) {}
|
||||
|
||||
public function create(Request $request): Response
|
||||
{
|
||||
Gate::authorize('create', NewsPost::class);
|
||||
|
||||
return $this->form($request, null);
|
||||
}
|
||||
|
||||
public function edit(Request $request, NewsPost $post): Response
|
||||
{
|
||||
Gate::authorize('update', $post);
|
||||
|
||||
return $this->form($request, $post);
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
Gate::authorize('create', NewsPost::class);
|
||||
|
||||
$post = new NewsPost(['author_id' => $request->user()->id]);
|
||||
|
||||
return $this->save($request, $post);
|
||||
}
|
||||
|
||||
public function update(Request $request, NewsPost $post): RedirectResponse
|
||||
{
|
||||
Gate::authorize('update', $post);
|
||||
|
||||
// Veröffentlichte Beiträge ändert nur, wer veröffentlichen darf – sonst gingen Änderungen ohne Freigabe online.
|
||||
if ($post->status === NewsPost::PUBLISHED && ! $this->policy->publish($request->user(), $post->category_id)) {
|
||||
abort(403, 'Veröffentlichte Beiträge kann nur die Redaktion ändern.');
|
||||
}
|
||||
|
||||
return $this->save($request, $post);
|
||||
}
|
||||
|
||||
public function approve(Request $request, NewsPost $post): RedirectResponse
|
||||
{
|
||||
Gate::authorize('update', $post);
|
||||
abort_unless($this->policy->publish($request->user(), $post->category_id), 403);
|
||||
|
||||
$data = $request->validate(['published_at' => ['nullable', 'date']]);
|
||||
$this->workflow->approve($post, $request->user(), isset($data['published_at']) ? Carbon::parse($data['published_at']) : null);
|
||||
|
||||
return to_route('editorial')->with('status', $post->isScheduled() ? 'Beitrag freigegeben und geplant.' : 'Beitrag veröffentlicht.');
|
||||
}
|
||||
|
||||
public function reject(Request $request, NewsPost $post): RedirectResponse
|
||||
{
|
||||
Gate::authorize('update', $post);
|
||||
abort_unless($this->policy->publish($request->user(), $post->category_id), 403);
|
||||
abort_unless($post->status === NewsPost::PENDING, 422);
|
||||
|
||||
$data = $request->validate(['note' => ['required', 'string', 'max:1000']], [], ['note' => 'Begründung']);
|
||||
$this->workflow->reject($post, $request->user(), $data['note']);
|
||||
|
||||
return to_route('editorial')->with('status', 'Beitrag zurückgegeben.');
|
||||
}
|
||||
|
||||
public function destroy(Request $request, NewsPost $post): RedirectResponse
|
||||
{
|
||||
Gate::authorize('delete', $post);
|
||||
|
||||
if ($post->status === NewsPost::PUBLISHED && ! $this->policy->publish($request->user(), $post->category_id)) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
$post->delete();
|
||||
Audit::log('news.deleted', ['post' => $post->id, 'title' => $post->title]);
|
||||
|
||||
return to_route('editorial')->with('status', 'Beitrag gelöscht.');
|
||||
}
|
||||
|
||||
public function uploadImage(Request $request, Images $images): JsonResponse
|
||||
{
|
||||
Gate::authorize('create', NewsPost::class);
|
||||
$request->validate(['image' => ['required', File::image()->types(['jpg', 'jpeg', 'png', 'webp', 'gif'])->max(15 * 1024)]]);
|
||||
|
||||
$path = $images->storeContentImage($request->file('image'), 'news/inline');
|
||||
|
||||
return response()->json(['path' => $path, 'url' => Storage::disk('uploads')->url($path)]);
|
||||
}
|
||||
|
||||
private function save(Request $request, NewsPost $post): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$writable = $this->writableCategoryIds($request);
|
||||
|
||||
$data = $request->validate([
|
||||
'title' => ['required', 'string', 'max:160'],
|
||||
'teaser' => ['nullable', 'string', 'max:300'],
|
||||
'body' => ['nullable', 'string', 'max:500000'],
|
||||
'category_id' => [$user->can('news.manage') ? 'nullable' : 'required', 'integer', Rule::in($writable === true ? NewsCategory::query()->pluck('id')->all() : $writable)],
|
||||
'cover' => ['nullable', File::image()->types(['jpg', 'jpeg', 'png', 'webp'])->max(10 * 1024)],
|
||||
'remove_cover' => ['boolean'],
|
||||
'is_featured' => ['boolean'],
|
||||
'published_at' => ['nullable', 'date'],
|
||||
'action' => ['required', Rule::in(['draft', 'submit', 'publish'])],
|
||||
], ['category_id.in' => 'In dieser Kategorie dürfen Sie keine Beiträge schreiben.'], ['category_id' => 'Kategorie', 'title' => 'Titel']);
|
||||
|
||||
$canPublish = $this->policy->publish($user, $data['category_id'] ?? null);
|
||||
|
||||
if ($data['action'] === 'publish' && ! $canPublish) {
|
||||
throw ValidationException::withMessages(['action' => 'In dieser Kategorie dürfen Sie nicht veröffentlichen. Bitte reichen Sie den Beitrag zur Freigabe ein.']);
|
||||
}
|
||||
|
||||
$post->fill([
|
||||
'title' => $data['title'],
|
||||
'teaser' => $data['teaser'] ?? null,
|
||||
'body' => $data['body'] ?? null,
|
||||
'category_id' => $data['category_id'] ?? null,
|
||||
]);
|
||||
|
||||
if ($canPublish) {
|
||||
$post->is_featured = (bool) ($data['is_featured'] ?? false);
|
||||
}
|
||||
|
||||
if ($request->boolean('remove_cover')) {
|
||||
$post->cover_path = null;
|
||||
}
|
||||
|
||||
if ($request->hasFile('cover')) {
|
||||
$post->cover_path = $request->file('cover')->store('news', 'uploads');
|
||||
}
|
||||
|
||||
if ($data['action'] === 'draft') {
|
||||
// Ein Entwurf ist nicht (mehr) veröffentlicht; eine laufende Freigabe bleibt bestehen.
|
||||
if ($post->status !== NewsPost::PENDING) {
|
||||
$post->published_at = null;
|
||||
$post->status = NewsPost::DRAFT;
|
||||
}
|
||||
}
|
||||
|
||||
$post->save();
|
||||
|
||||
if ($data['action'] === 'submit') {
|
||||
$count = $this->workflow->submit($post, $user);
|
||||
$message = $count > 0
|
||||
? "Zur Freigabe eingereicht – {$count} ".($count === 1 ? 'Person wurde' : 'Personen wurden').' benachrichtigt.'
|
||||
: 'Zur Freigabe eingereicht.';
|
||||
} elseif ($data['action'] === 'publish') {
|
||||
$this->workflow->approve($post, $user, isset($data['published_at']) ? Carbon::parse($data['published_at']) : null);
|
||||
$message = $post->isScheduled() ? 'Beitrag geplant.' : 'Beitrag veröffentlicht.';
|
||||
} else {
|
||||
$message = 'Entwurf gespeichert.';
|
||||
}
|
||||
|
||||
return to_route('news.editor.edit', $post)->with('status', $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<int>|true
|
||||
*/
|
||||
private function writableCategoryIds(Request $request): array|true
|
||||
{
|
||||
return $request->user()->can('news.manage') ? true : $request->user()->permissions()->ids('news.post.create', 'news_category');
|
||||
}
|
||||
|
||||
private function form(Request $request, ?NewsPost $post): Response
|
||||
{
|
||||
$user = $request->user();
|
||||
$writable = $this->writableCategoryIds($request);
|
||||
$categories = NewsCategory::query()->orderBy('sort')->orderBy('name')
|
||||
->when($writable !== true, fn ($q) => $q->whereIn('id', $writable))
|
||||
->get(['id', 'name']);
|
||||
|
||||
return Inertia::render('news::Editor', [
|
||||
'post' => $post ? [
|
||||
'id' => $post->id,
|
||||
'title' => $post->title,
|
||||
'teaser' => $post->teaser,
|
||||
'body' => $post->body,
|
||||
'category_id' => $post->category_id,
|
||||
'cover_url' => $post->coverUrl('large'),
|
||||
'is_featured' => $post->is_featured,
|
||||
'published_at' => $post->published_at?->toIso8601String(),
|
||||
'status' => $post->status,
|
||||
'status_label' => $post->statusLabel(),
|
||||
'is_published' => $post->isPublished(),
|
||||
'url' => $post->isPublished() ? route('news.show', $post) : null,
|
||||
'review_note' => $post->review_note,
|
||||
'author' => $post->author?->name,
|
||||
] : null,
|
||||
'categories' => $categories->map(fn (NewsCategory $c) => [
|
||||
'id' => $c->id,
|
||||
'name' => $c->name,
|
||||
'can_publish' => $this->policy->publish($user, $c->id),
|
||||
]),
|
||||
'canPublishWithoutCategory' => $user->can('news.manage'),
|
||||
'canDelete' => $post && $user->can('delete', $post) && ($post->status !== NewsPost::PUBLISHED || $this->policy->publish($user, $post->category_id)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -22,6 +22,12 @@ class NewsPost extends Model
|
|||
{
|
||||
use HasFactory;
|
||||
|
||||
public const DRAFT = 'draft';
|
||||
|
||||
public const PENDING = 'pending';
|
||||
|
||||
public const PUBLISHED = 'published';
|
||||
|
||||
protected static function newFactory(): NewsPostFactory
|
||||
{
|
||||
return NewsPostFactory::new();
|
||||
|
|
@ -34,6 +40,13 @@ class NewsPost extends Model
|
|||
$post->slug = static::uniqueSlug($post->title, $post->getKey());
|
||||
}
|
||||
|
||||
// Ein Veröffentlichungsdatum bedeutet „veröffentlicht“ (bzw. geplant) – auch aus dem Admin-Formular.
|
||||
if ($post->published_at !== null) {
|
||||
$post->status = self::PUBLISHED;
|
||||
} elseif ($post->status === self::PUBLISHED || $post->status === null) {
|
||||
$post->status = self::DRAFT;
|
||||
}
|
||||
|
||||
if ($post->isDirty('body') || $post->body_html === null) {
|
||||
$richText = app(RichText::class);
|
||||
$post->body_html = $richText->toSafeHtml($post->body);
|
||||
|
|
@ -66,6 +79,7 @@ class NewsPost extends Model
|
|||
return [
|
||||
'is_featured' => 'boolean',
|
||||
'published_at' => 'datetime',
|
||||
'submitted_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
|
|
@ -77,6 +91,14 @@ class NewsPost extends Model
|
|||
return $this->belongsTo(NewsCategory::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function reviewer(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'reviewed_by');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
|
|
@ -92,12 +114,27 @@ class NewsPost extends Model
|
|||
*/
|
||||
public function scopePublished(Builder $query): void
|
||||
{
|
||||
$query->whereNotNull('published_at')->where('published_at', '<=', now());
|
||||
$query->where('news_posts.status', self::PUBLISHED)->whereNotNull('published_at')->where('published_at', '<=', now());
|
||||
}
|
||||
|
||||
public function isPublished(): bool
|
||||
{
|
||||
return $this->published_at !== null && $this->published_at->isPast();
|
||||
return $this->status === self::PUBLISHED && $this->published_at !== null && $this->published_at->isPast();
|
||||
}
|
||||
|
||||
public function isScheduled(): bool
|
||||
{
|
||||
return $this->status === self::PUBLISHED && $this->published_at?->isFuture();
|
||||
}
|
||||
|
||||
public function statusLabel(): string
|
||||
{
|
||||
return match (true) {
|
||||
$this->status === self::PENDING => 'Zur Freigabe',
|
||||
$this->isScheduled() => 'Geplant',
|
||||
$this->isPublished() => 'Veröffentlicht',
|
||||
default => 'Entwurf',
|
||||
};
|
||||
}
|
||||
|
||||
public function coverUrl(string $variant = 'large'): ?string
|
||||
|
|
|
|||
|
|
@ -3,7 +3,11 @@
|
|||
namespace Inhaus\Plugins\News;
|
||||
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Editorial\Editorial;
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Blocks;
|
||||
use App\Pagebuilder\BlockType;
|
||||
use App\Pagebuilder\Field;
|
||||
use App\Plugins\Plugin;
|
||||
use App\Support\Abilities;
|
||||
use App\Support\Navigation;
|
||||
|
|
@ -20,7 +24,7 @@ class NewsPlugin extends Plugin
|
|||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->app->make(Navigation::class)->add('news', 'Neuigkeiten', '/neuigkeiten', active: 'news.*', sort: 20);
|
||||
$this->app->make(Navigation::class)->add('news', 'Neuigkeiten', '/neuigkeiten', active: ['news.index', 'news.show'], sort: 20);
|
||||
|
||||
$abilities = $this->app->make(Abilities::class);
|
||||
$abilities->define('news.manage', 'Neuigkeiten: alle Kategorien verwalten', 'Neuigkeiten');
|
||||
|
|
@ -32,6 +36,34 @@ class NewsPlugin extends Plugin
|
|||
Gate::policy(NewsPost::class, NewsPostPolicy::class);
|
||||
|
||||
$this->registerWidgets($this->app->make(Widgets::class));
|
||||
|
||||
$this->app->make(Editorial::class)->add(
|
||||
'news',
|
||||
'Neuigkeiten',
|
||||
'news::EditorialNews',
|
||||
10,
|
||||
fn (User $user) => app(NewsPostPolicy::class)->viewAny($user),
|
||||
fn (User $user) => EditorialNews::props($user),
|
||||
);
|
||||
|
||||
$this->app->make(Blocks::class)->add(BlockType::make('news.latest', 'Neuigkeiten', 'newspaper', 'dynamic', 'news::LatestNews')
|
||||
->description('Die neuesten Beiträge – optional nur aus einer Kategorie.')
|
||||
->fields([
|
||||
Field::text('title', 'Überschrift', 150, 'Neuigkeiten'),
|
||||
Field::select('category', 'Kategorie', fn () => ['' => 'Alle Kategorien'] + NewsCategory::query()->orderBy('sort')->pluck('name', 'slug')->all(), ''),
|
||||
Field::number('count', 'Anzahl', 1, 12, 3),
|
||||
Field::select('layout', 'Darstellung', ['cards' => 'Kacheln', 'list' => 'Liste'], 'cards'),
|
||||
])
|
||||
->resolveUsing(function (array $data, ?User $user) {
|
||||
$posts = NewsPost::query()->published()->visibleTo($user)->with('category')
|
||||
->when($data['category'], fn ($q, $slug) => $q->whereHas('category', fn ($c) => $c->where('slug', $slug)))
|
||||
->latest('published_at')->limit($data['count'])->get();
|
||||
|
||||
return [
|
||||
'posts' => NewsPostResource::collection($posts)->resolve(),
|
||||
'more_url' => '/neuigkeiten'.($data['category'] ? '?kategorie='.$data['category'] : ''),
|
||||
];
|
||||
}));
|
||||
}
|
||||
|
||||
private function registerWidgets(Widgets $widgets): void
|
||||
|
|
|
|||
95
plugins-core/news/src/NewsWorkflow.php
Normal file
95
plugins-core/news/src/NewsWorkflow.php
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\News;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Notifications\PortalNotification;
|
||||
use App\Support\Audit;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
|
||||
/**
|
||||
* Freigabe-Workflow für Beiträge: Einreichen, Freigeben, Zurückgeben –
|
||||
* mit Benachrichtigungen an Redaktion bzw. Autorin/Autor.
|
||||
*/
|
||||
class NewsWorkflow
|
||||
{
|
||||
public function submit(NewsPost $post, User $user): int
|
||||
{
|
||||
$post->forceFill(['status' => NewsPost::PENDING, 'submitted_at' => now(), 'published_at' => null, 'review_note' => null])->save();
|
||||
|
||||
$recipients = $this->publishers($post->category_id, $user);
|
||||
|
||||
Notification::send($recipients, new PortalNotification(
|
||||
'Beitrag zur Freigabe: '.$post->title,
|
||||
$user->name.' hat einen Beitrag eingereicht.',
|
||||
route('news.editor.edit', $post),
|
||||
'file-check',
|
||||
));
|
||||
|
||||
Audit::log('news.submitted', ['post' => $post->id, 'title' => $post->title]);
|
||||
|
||||
return $recipients->count();
|
||||
}
|
||||
|
||||
public function approve(NewsPost $post, User $reviewer, ?\DateTimeInterface $at = null): void
|
||||
{
|
||||
$wasPending = $post->status === NewsPost::PENDING;
|
||||
|
||||
$post->forceFill([
|
||||
'status' => NewsPost::PUBLISHED,
|
||||
'published_at' => $at ?? now(),
|
||||
'reviewed_by' => $reviewer->id,
|
||||
'review_note' => null,
|
||||
])->save();
|
||||
|
||||
if ($wasPending && $post->author && ! $post->author->is($reviewer)) {
|
||||
$post->author->notify(new PortalNotification(
|
||||
($post->isScheduled() ? 'Beitrag freigegeben und geplant: ' : 'Beitrag veröffentlicht: ').$post->title,
|
||||
'Freigegeben von '.$reviewer->name.'.',
|
||||
$post->isScheduled() ? route('news.editor.edit', $post) : route('news.show', $post),
|
||||
'newspaper',
|
||||
));
|
||||
}
|
||||
|
||||
Audit::log('news.published', ['post' => $post->id, 'title' => $post->title, 'at' => $post->published_at?->toIso8601String()]);
|
||||
}
|
||||
|
||||
public function reject(NewsPost $post, User $reviewer, string $note): void
|
||||
{
|
||||
$post->forceFill(['status' => NewsPost::DRAFT, 'published_at' => null, 'reviewed_by' => $reviewer->id, 'review_note' => $note])->save();
|
||||
|
||||
$post->author?->notify(new PortalNotification(
|
||||
'Beitrag zurückgegeben: '.$post->title,
|
||||
$reviewer->name.': '.$note,
|
||||
route('news.editor.edit', $post),
|
||||
'undo',
|
||||
));
|
||||
|
||||
Audit::log('news.returned', ['post' => $post->id, 'title' => $post->title]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wer in der Kategorie veröffentlichen darf.
|
||||
*
|
||||
* @return Collection<int, User>
|
||||
*/
|
||||
public function publishers(?int $categoryId, ?User $except = null): Collection
|
||||
{
|
||||
$roleIds = DB::table('grants')
|
||||
->where(function ($q) use ($categoryId) {
|
||||
$q->whereIn('ability', ['*', 'news.manage'])->whereNull('resource_type');
|
||||
$q->orWhere(fn ($q) => $q->where('ability', 'news.post.publish')->where('resource_type', 'news_category')
|
||||
->where(fn ($q) => $q->whereNull('resource_id')->when($categoryId, fn ($q) => $q->orWhere('resource_id', $categoryId))));
|
||||
})
|
||||
->pluck('role_id');
|
||||
|
||||
return User::query()->active()
|
||||
->whereIn('id', DB::table('role_user')->whereIn('role_id', $roleIds)->select('user_id'))
|
||||
->when($except, fn ($q) => $q->whereKeyNot($except->id))
|
||||
->limit(50)
|
||||
->get();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
<?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('pages', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('parent_id')->nullable()->constrained('pages')->restrictOnDelete();
|
||||
$table->string('title');
|
||||
$table->string('slug', 120);
|
||||
// Vollständige Adresse ab /seiten/, z. B. „mav/wahlen“ – für schnelle Aufrufe ohne Baumsuche.
|
||||
$table->string('path', 400)->unique();
|
||||
$table->unsignedInteger('sort')->default(0);
|
||||
$table->boolean('in_navigation')->default(false);
|
||||
|
||||
// Veröffentlichter Stand (bereinigtes Block-JSON). null = nie veröffentlicht.
|
||||
$table->json('content')->nullable();
|
||||
$table->timestamp('published_at')->nullable();
|
||||
$table->foreignId('published_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
|
||||
// Entwurf: Änderungen, die noch nicht veröffentlicht sind. null = keine.
|
||||
$table->string('draft_title')->nullable();
|
||||
$table->json('draft')->nullable();
|
||||
$table->timestamp('draft_updated_at')->nullable();
|
||||
$table->foreignId('draft_updated_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
|
||||
// Zeitgesteuerte Veröffentlichung eines Entwurfsstands.
|
||||
$table->timestamp('scheduled_at')->nullable()->index();
|
||||
$table->string('scheduled_title')->nullable();
|
||||
$table->json('scheduled_content')->nullable();
|
||||
$table->foreignId('scheduled_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
|
||||
// Bearbeitungssperre: verhindert, dass zwei Personen gleichzeitig ändern.
|
||||
$table->foreignId('locked_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamp('locked_until')->nullable();
|
||||
|
||||
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['parent_id', 'slug']);
|
||||
$table->index(['parent_id', 'sort']);
|
||||
});
|
||||
|
||||
Schema::create('page_revisions', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('page_id')->constrained('pages')->cascadeOnDelete();
|
||||
$table->string('title');
|
||||
$table->json('content');
|
||||
$table->string('action', 20)->default('published');
|
||||
$table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamp('created_at')->nullable();
|
||||
|
||||
$table->index(['page_id', 'id']);
|
||||
});
|
||||
|
||||
Schema::create('page_files', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('page_id')->constrained('pages')->cascadeOnDelete();
|
||||
$table->string('name');
|
||||
$table->string('path');
|
||||
$table->string('mime', 150)->nullable();
|
||||
$table->unsignedBigInteger('size')->default(0);
|
||||
$table->foreignId('uploaded_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('page_files');
|
||||
Schema::dropIfExists('page_revisions');
|
||||
Schema::dropIfExists('pages');
|
||||
}
|
||||
};
|
||||
13
plugins-core/pages/plugin.json
Normal file
13
plugins-core/pages/plugin.json
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"slug": "pages",
|
||||
"name": "Seiten",
|
||||
"version": "1.0.0",
|
||||
"description": "Inhaltsseiten mit Seitenbaum, Pagebuilder, Versionen und Freigabe – z. B. für Abteilungen, MAV oder Handbücher.",
|
||||
"author": "Inhaus",
|
||||
"namespace": "Inhaus\\Plugins\\Pages\\",
|
||||
"class": "Inhaus\\Plugins\\Pages\\PagesPlugin",
|
||||
"requires": {
|
||||
"core": ">=0.5.0",
|
||||
"php": ">=8.3"
|
||||
}
|
||||
}
|
||||
26
plugins-core/pages/resources/js/blocks/Downloads.vue
Normal file
26
plugins-core/pages/resources/js/blocks/Downloads.vue
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<script setup>
|
||||
import { Download, FileText } from '@lucide/vue';
|
||||
|
||||
defineProps({ block: { type: Object, required: true } });
|
||||
|
||||
const formatSize = (bytes) => (bytes > 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1).replace('.', ',')} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section>
|
||||
<h3 v-if="block.data.title" class="mb-3 text-lg font-semibold">{{ block.data.title }}</h3>
|
||||
<ul class="divide-y rounded-lg border bg-card">
|
||||
<li v-for="file in block.props?.files ?? []" :key="file.id">
|
||||
<a :href="file.url" class="group flex items-center gap-3 px-4 py-3 hover:bg-accent/50">
|
||||
<span class="grid size-10 shrink-0 place-items-center rounded-md bg-brand-soft text-brand-text"><FileText class="size-5" /></span>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block truncate text-sm font-medium group-hover:underline">{{ file.name }}</span>
|
||||
<span class="block text-xs text-muted-foreground">{{ file.extension || 'Datei' }} · {{ formatSize(file.size) }}</span>
|
||||
</span>
|
||||
<Download class="size-4 shrink-0 text-muted-foreground" />
|
||||
</a>
|
||||
</li>
|
||||
<li v-if="!(block.props?.files ?? []).length" class="px-4 py-3 text-sm text-muted-foreground">Noch keine Dateien.</li>
|
||||
</ul>
|
||||
</section>
|
||||
</template>
|
||||
26
plugins-core/pages/resources/js/blocks/Subpages.vue
Normal file
26
plugins-core/pages/resources/js/blocks/Subpages.vue
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { ChevronRight, FileText } from '@lucide/vue';
|
||||
|
||||
defineProps({ block: { type: Object, required: true } });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section>
|
||||
<h3 v-if="block.data.title" class="mb-3 text-lg font-semibold">{{ block.data.title }}</h3>
|
||||
<div :class="block.data.layout === 'list' ? 'divide-y rounded-lg border bg-card' : 'grid gap-3 @xl:grid-cols-2 @4xl:grid-cols-3'">
|
||||
<Link
|
||||
v-for="page in block.props?.pages ?? []"
|
||||
:key="page.id"
|
||||
:href="page.url"
|
||||
class="group flex items-center gap-3 hover:bg-accent/50"
|
||||
:class="block.data.layout === 'list' ? 'px-4 py-3' : 'rounded-lg border bg-card p-4'"
|
||||
>
|
||||
<FileText class="size-5 shrink-0 text-brand-text" />
|
||||
<span class="min-w-0 flex-1 truncate font-medium group-hover:underline">{{ page.title }}</span>
|
||||
<ChevronRight class="size-4 text-muted-foreground" />
|
||||
</Link>
|
||||
<p v-if="!(block.props?.pages ?? []).length" class="text-sm text-muted-foreground" :class="block.data.layout === 'list' ? 'px-4 py-3' : ''">Keine veröffentlichten Unterseiten.</p>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
47
plugins-core/pages/resources/js/components/NewPageDialog.vue
Normal file
47
plugins-core/pages/resources/js/components/NewPageDialog.vue
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
<script setup>
|
||||
import { ref, watch } from 'vue';
|
||||
import { useForm } from '@inertiajs/vue3';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
const props = defineProps({
|
||||
parentId: { type: Number, default: null },
|
||||
parentTitle: { type: String, default: '' },
|
||||
});
|
||||
|
||||
const open = defineModel('open', { type: Boolean, default: false });
|
||||
const emit = defineEmits(['before-create']);
|
||||
const form = useForm({ title: '', parent_id: null });
|
||||
|
||||
watch(open, (value) => value && (form.reset(), form.clearErrors()));
|
||||
|
||||
async function create() {
|
||||
emit('before-create');
|
||||
form.parent_id = props.parentId;
|
||||
form.post('/redaktion/seiten');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog v-model:open="open">
|
||||
<DialogContent class="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ parentId ? 'Unterseite anlegen' : 'Neue Seite' }}</DialogTitle>
|
||||
<DialogDescription v-if="parentId">Unter „{{ parentTitle }}“. Die Seite ist erst nach dem Veröffentlichen sichtbar.</DialogDescription>
|
||||
<DialogDescription v-else>Auf der obersten Ebene. Die Seite ist erst nach dem Veröffentlichen sichtbar.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form class="grid gap-4" @submit.prevent="create">
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Titel</span>
|
||||
<Input v-model="form.title" maxlength="200" autofocus :aria-invalid="!!form.errors.title" />
|
||||
<span v-if="form.errors.title" class="text-[13px] text-destructive">{{ form.errors.title }}</span>
|
||||
</label>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" @click="open = false">Abbrechen</Button>
|
||||
<Button type="submit" :disabled="form.processing || !form.title.trim()">Anlegen und bearbeiten</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
<script setup>
|
||||
import { ref, watch } from 'vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { http } from '@/lib/http';
|
||||
|
||||
const props = defineProps({
|
||||
page: { type: Object, required: true },
|
||||
base: { type: String, required: true },
|
||||
});
|
||||
|
||||
const open = defineModel('open', { type: Boolean, default: false });
|
||||
const emit = defineEmits(['saved']);
|
||||
|
||||
const form = ref({ slug: '', in_navigation: false });
|
||||
const errors = ref({});
|
||||
const busy = ref(false);
|
||||
|
||||
watch(open, (value) => {
|
||||
if (value) {
|
||||
form.value = { slug: props.page.slug, in_navigation: props.page.in_navigation };
|
||||
errors.value = {};
|
||||
}
|
||||
});
|
||||
|
||||
async function save() {
|
||||
busy.value = true;
|
||||
|
||||
try {
|
||||
emit('saved', await http.put(`${props.base}/einstellungen`, form.value));
|
||||
open.value = false;
|
||||
} catch (error) {
|
||||
errors.value = error.fieldErrors ?? {};
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog v-model:open="open">
|
||||
<DialogContent class="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Seiteneinstellungen</DialogTitle>
|
||||
<DialogDescription>Sichtbarkeit und Rechte pflegen Sie in der Administration unter „Seiten“.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form class="grid gap-4" @submit.prevent="save">
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Kürzel in der Adresse</span>
|
||||
<Input v-model="form.slug" maxlength="120" :aria-invalid="!!errors.slug" />
|
||||
<span v-if="errors.slug" class="text-[13px] text-destructive">{{ errors.slug }}</span>
|
||||
<span v-else class="text-xs text-muted-foreground">Ändert auch die Adressen aller Unterseiten. Alte Links funktionieren dann nicht mehr.</span>
|
||||
</label>
|
||||
<label v-if="page.can.navigation" class="flex items-center justify-between gap-3 text-[13px] font-medium">
|
||||
In der Hauptnavigation anzeigen
|
||||
<Switch v-model="form.in_navigation" />
|
||||
</label>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" @click="open = false">Abbrechen</Button>
|
||||
<Button type="submit" :disabled="busy">Speichern</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
27
plugins-core/pages/resources/js/components/PageTreeNav.vue
Normal file
27
plugins-core/pages/resources/js/components/PageTreeNav.vue
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
|
||||
defineProps({
|
||||
items: { type: Array, required: true },
|
||||
current: { type: String, required: true },
|
||||
depth: { type: Number, default: 0 },
|
||||
});
|
||||
|
||||
const contains = (item, url) => item.url === url || item.children.some((child) => contains(child, url));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ul class="grid gap-0.5" :class="depth ? 'mt-0.5 ml-3 border-l pl-2' : 'mt-1'">
|
||||
<li v-for="item in items" :key="item.id">
|
||||
<Link
|
||||
:href="item.url"
|
||||
class="block rounded-md px-3 py-1.5 text-sm"
|
||||
:class="item.url === current ? 'bg-brand-soft font-medium text-brand-soft-foreground' : 'text-foreground/80 hover:bg-accent hover:text-foreground'"
|
||||
:aria-current="item.url === current ? 'page' : undefined"
|
||||
>
|
||||
{{ item.title }}
|
||||
</Link>
|
||||
<PageTreeNav v-if="item.children.length && contains(item, current)" :items="item.children" :current="current" :depth="depth + 1" />
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
78
plugins-core/pages/resources/js/components/PublishDialog.vue
Normal file
78
plugins-core/pages/resources/js/components/PublishDialog.vue
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
<script setup>
|
||||
import { ref, watch } from 'vue';
|
||||
import { CalendarClock, Send } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
const props = defineProps({
|
||||
scheduledAt: { type: String, default: null },
|
||||
});
|
||||
|
||||
const open = defineModel('open', { type: Boolean, default: false });
|
||||
const emit = defineEmits(['publish']);
|
||||
|
||||
const mode = ref('now');
|
||||
const when = ref('');
|
||||
const busy = ref(false);
|
||||
|
||||
function localValue(date) {
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
||||
}
|
||||
|
||||
watch(open, (value) => {
|
||||
if (value) {
|
||||
mode.value = 'now';
|
||||
const next = new Date(Date.now() + 24 * 3600 * 1000);
|
||||
next.setHours(7, 0, 0, 0);
|
||||
when.value = localValue(next);
|
||||
busy.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function submit() {
|
||||
busy.value = true;
|
||||
emit('publish', mode.value === 'later' ? new Date(when.value).toISOString() : null);
|
||||
setTimeout(() => (busy.value = false), 800);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog v-model:open="open">
|
||||
<DialogContent class="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Seite veröffentlichen</DialogTitle>
|
||||
<DialogDescription>Der aktuelle Stand wird für alle sichtbar, die die Seite sehen dürfen. Frühere Stände bleiben unter „Versionen“ erhalten.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<p v-if="props.scheduledAt" class="rounded-md bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:bg-amber-950/50 dark:text-amber-100">
|
||||
Es ist bereits eine Veröffentlichung geplant. Sie wird durch diese ersetzt.
|
||||
</p>
|
||||
|
||||
<fieldset class="grid gap-2">
|
||||
<legend class="sr-only">Zeitpunkt</legend>
|
||||
<label class="flex cursor-pointer items-start gap-3 rounded-md border p-3 has-checked:border-brand-400 has-checked:bg-brand-soft/60">
|
||||
<input v-model="mode" type="radio" value="now" class="mt-1 accent-[var(--brand)]" />
|
||||
<span><span class="block text-sm font-medium">Jetzt veröffentlichen</span><span class="block text-xs text-muted-foreground">Sofort sichtbar.</span></span>
|
||||
</label>
|
||||
<label class="flex cursor-pointer items-start gap-3 rounded-md border p-3 has-checked:border-brand-400 has-checked:bg-brand-soft/60">
|
||||
<input v-model="mode" type="radio" value="later" class="mt-1 accent-[var(--brand)]" />
|
||||
<span class="grid flex-1 gap-2">
|
||||
<span><span class="block text-sm font-medium">Zeitgesteuert</span><span class="block text-xs text-muted-foreground">Der aktuelle Stand geht zum gewählten Zeitpunkt online.</span></span>
|
||||
<Input v-if="mode === 'later'" v-model="when" type="datetime-local" :min="localValue(new Date())" aria-label="Zeitpunkt der Veröffentlichung" />
|
||||
</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="open = false">Abbrechen</Button>
|
||||
<Button :disabled="busy || (mode === 'later' && !when)" @click="submit">
|
||||
<CalendarClock v-if="mode === 'later'" /><Send v-else />
|
||||
{{ mode === 'later' ? 'Planen' : 'Veröffentlichen' }}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
39
plugins-core/pages/resources/js/components/ReviewDialog.vue
Normal file
39
plugins-core/pages/resources/js/components/ReviewDialog.vue
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<script setup>
|
||||
import { ref, watch } from 'vue';
|
||||
import { Send } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
|
||||
const open = defineModel('open', { type: Boolean, default: false });
|
||||
const emit = defineEmits(['submit']);
|
||||
const message = ref('');
|
||||
const busy = ref(false);
|
||||
|
||||
watch(open, (value) => value && ((message.value = ''), (busy.value = false)));
|
||||
|
||||
function submit() {
|
||||
busy.value = true;
|
||||
emit('submit', message.value);
|
||||
setTimeout(() => (busy.value = false), 1500);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog v-model:open="open">
|
||||
<DialogContent class="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Freigabe anfordern</DialogTitle>
|
||||
<DialogDescription>Ihre Änderungen sind als Entwurf gespeichert. Die Personen, die diese Seite veröffentlichen dürfen, werden benachrichtigt.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Nachricht (freiwillig)</span>
|
||||
<Textarea v-model="message" rows="3" maxlength="1000" placeholder="z. B. Bitte bis Freitag veröffentlichen." />
|
||||
</label>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="open = false">Abbrechen</Button>
|
||||
<Button :disabled="busy" @click="submit"><Send /> Anfordern</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
<script setup>
|
||||
import { ref, watch } from 'vue';
|
||||
import { History, LoaderCircle } from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import PageContent from '@/pagebuilder/PageContent.vue';
|
||||
import { http } from '@/lib/http';
|
||||
import { formatRelative } from '@/lib/format';
|
||||
|
||||
const props = defineProps({
|
||||
base: { type: String, required: true },
|
||||
readOnly: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const open = defineModel('open', { type: Boolean, default: false });
|
||||
const emit = defineEmits(['restored']);
|
||||
|
||||
const revisions = ref(null);
|
||||
const active = ref(null);
|
||||
const preview = ref(null);
|
||||
const loading = ref(false);
|
||||
|
||||
watch(open, async (value) => {
|
||||
if (!value) return;
|
||||
|
||||
revisions.value = null;
|
||||
preview.value = null;
|
||||
active.value = null;
|
||||
revisions.value = (await http.get(`${props.base}/versionen`)).revisions;
|
||||
|
||||
if (revisions.value.length) show(revisions.value[0]);
|
||||
});
|
||||
|
||||
async function show(revision) {
|
||||
active.value = revision;
|
||||
loading.value = true;
|
||||
|
||||
try {
|
||||
preview.value = await http.get(`${props.base}/versionen/${revision.id}`);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function restore() {
|
||||
try {
|
||||
emit('restored', await http.post(`${props.base}/versionen/${active.value.id}/wiederherstellen`));
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog v-model:open="open">
|
||||
<DialogContent class="flex h-[85vh] max-w-5xl flex-col gap-0 p-0 sm:max-w-5xl">
|
||||
<DialogHeader class="border-b px-5 py-4">
|
||||
<DialogTitle>Versionen</DialogTitle>
|
||||
<DialogDescription>Jede Veröffentlichung wird gespeichert. Eine ältere Version lässt sich als Entwurf zurückholen.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div class="flex min-h-0 flex-1">
|
||||
<ul class="w-64 shrink-0 overflow-y-auto border-r p-2">
|
||||
<li v-if="revisions === null" class="grid place-items-center py-10"><LoaderCircle class="size-5 animate-spin text-muted-foreground" /></li>
|
||||
<li v-else-if="!revisions.length" class="px-3 py-6 text-center text-sm text-muted-foreground">Noch keine veröffentlichten Versionen.</li>
|
||||
<li v-for="revision in revisions ?? []" :key="revision.id">
|
||||
<button
|
||||
type="button"
|
||||
class="w-full rounded-md px-3 py-2 text-left"
|
||||
:class="active?.id === revision.id ? 'bg-brand-soft text-brand-soft-foreground' : 'hover:bg-accent'"
|
||||
@click="show(revision)"
|
||||
>
|
||||
<span class="block text-sm font-medium">{{ formatRelative(revision.created_at) }}</span>
|
||||
<span class="block truncate text-xs text-muted-foreground">{{ revision.action }}<template v-if="revision.user"> · {{ revision.user }}</template></span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="flex min-w-0 flex-1 flex-col">
|
||||
<div class="min-h-0 flex-1 overflow-y-auto bg-background p-6">
|
||||
<div v-if="loading" class="grid place-items-center py-16"><LoaderCircle class="size-6 animate-spin text-muted-foreground" /></div>
|
||||
<template v-else-if="preview">
|
||||
<h1 class="mb-6 text-2xl font-semibold tracking-tight">{{ preview.title }}</h1>
|
||||
<PageContent :content="preview.content" />
|
||||
</template>
|
||||
</div>
|
||||
<div v-if="active" class="flex items-center justify-between gap-3 border-t px-5 py-3">
|
||||
<span class="text-xs text-muted-foreground">{{ new Date(active.created_at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' }) }}</span>
|
||||
<Button :disabled="readOnly" @click="restore"><History /> Als Entwurf wiederherstellen</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
45
plugins-core/pages/resources/js/editorial/EditorialPages.vue
Normal file
45
plugins-core/pages/resources/js/editorial/EditorialPages.vue
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
<script setup>
|
||||
import { ref } from 'vue';
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { Lock, Plus } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import { formatRelative } from '@/lib/format';
|
||||
import NewPageDialog from '../components/NewPageDialog.vue';
|
||||
|
||||
defineProps({
|
||||
pages: { type: Array, required: true },
|
||||
canCreate: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const creating = ref(false);
|
||||
|
||||
const statuses = {
|
||||
published: { label: 'Veröffentlicht', class: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-200' },
|
||||
draft: { label: 'Entwurf', class: 'bg-brand-soft text-brand-soft-foreground' },
|
||||
scheduled: { label: 'Geplant', class: 'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-200' },
|
||||
new: { label: 'Neu', class: 'bg-muted text-muted-foreground' },
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Panel title="Seiten">
|
||||
<template #actions>
|
||||
<Button v-if="canCreate" size="sm" variant="outline" @click="creating = true"><Plus /> Neue Seite</Button>
|
||||
</template>
|
||||
<ul v-if="pages.length" class="-mx-5 divide-y border-t">
|
||||
<li v-for="page in pages" :key="page.id" class="flex items-center gap-3 py-2.5 pr-5" :style="{ paddingLeft: `${1.25 + Math.min(page.depth, 4) * 1.25}rem` }">
|
||||
<div class="min-w-0 flex-1" :class="page.depth ? 'border-l pl-3' : ''">
|
||||
<Link :href="page.edit_url" class="block truncate text-sm font-medium hover:underline">{{ page.title }}</Link>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
{{ page.url }}<template v-if="page.changed_at"> · {{ formatRelative(page.changed_at) }}</template>
|
||||
</p>
|
||||
</div>
|
||||
<span v-if="page.locked_by" class="inline-flex items-center gap-1 text-xs text-muted-foreground" :title="`${page.locked_by} bearbeitet gerade`"><Lock class="size-3.5" /> {{ page.locked_by }}</span>
|
||||
<span class="shrink-0 rounded px-1.5 py-0.5 text-[11px] font-medium" :class="statuses[page.status].class">{{ statuses[page.status].label }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="text-sm text-muted-foreground">Sie dürfen noch keine Seiten bearbeiten.</p>
|
||||
<NewPageDialog v-model:open="creating" />
|
||||
</Panel>
|
||||
</template>
|
||||
636
plugins-core/pages/resources/js/pages/Editor.vue
Normal file
636
plugins-core/pages/resources/js/pages/Editor.vue
Normal file
|
|
@ -0,0 +1,636 @@
|
|||
<script setup>
|
||||
import { computed, onBeforeUnmount, onMounted, provide, reactive, ref, watch } from 'vue';
|
||||
import { Head, Link, router } from '@inertiajs/vue3';
|
||||
import {
|
||||
ArrowLeft,
|
||||
CalendarClock,
|
||||
CircleCheck,
|
||||
CloudAlert,
|
||||
EllipsisVertical,
|
||||
Eye,
|
||||
FilePlus2,
|
||||
History,
|
||||
LoaderCircle,
|
||||
Lock,
|
||||
Monitor,
|
||||
Redo2,
|
||||
Send,
|
||||
Settings2,
|
||||
Smartphone,
|
||||
Tablet,
|
||||
Trash2,
|
||||
Undo2,
|
||||
} from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Toaster } from '@/components/ui/sonner';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
|
||||
import BlockPalette from '@/pagebuilder/editor/BlockPalette.vue';
|
||||
import BlockSettings from '@/pagebuilder/editor/BlockSettings.vue';
|
||||
import EditorBlockList from '@/pagebuilder/editor/EditorBlockList.vue';
|
||||
import { clone, createBlock, duplicate as duplicateBlock, locate, walk } from '@/pagebuilder/editor/tree';
|
||||
import { http } from '@/lib/http';
|
||||
import { formatTime } from '@/lib/format';
|
||||
import PublishDialog from '../components/PublishDialog.vue';
|
||||
import RevisionsDialog from '../components/RevisionsDialog.vue';
|
||||
import PageSettingsDialog from '../components/PageSettingsDialog.vue';
|
||||
import ReviewDialog from '../components/ReviewDialog.vue';
|
||||
import NewPageDialog from '../components/NewPageDialog.vue';
|
||||
|
||||
const props = defineProps({
|
||||
page: { type: Object, required: true },
|
||||
working: { type: Object, required: true },
|
||||
lockedBy: { type: Object, default: null },
|
||||
blockTypes: { type: Array, required: true },
|
||||
blockGroups: { type: Object, required: true },
|
||||
files: { type: Array, default: () => [] },
|
||||
audienceOptions: { type: Object, required: true },
|
||||
breadcrumbs: { type: Array, default: () => [] },
|
||||
uploadsUrl: { type: String, required: true },
|
||||
});
|
||||
|
||||
const base = `/redaktion/seiten/${props.page.id}`;
|
||||
const types = Object.fromEntries(props.blockTypes.map((type) => [type.key, type]));
|
||||
|
||||
const page = ref(props.page);
|
||||
const working = reactive(clone(props.working));
|
||||
const selectedId = ref(null);
|
||||
const hoveredId = ref(null);
|
||||
const previews = reactive({});
|
||||
const files = ref(props.files);
|
||||
const readOnly = ref(!!props.lockedBy);
|
||||
const lockedBy = ref(props.lockedBy);
|
||||
const device = ref('desktop');
|
||||
const sheetOpen = ref(false);
|
||||
const sidebarTab = ref('blocks');
|
||||
|
||||
const selected = computed(() => (selectedId.value ? locate(working.content.blocks, selectedId.value)?.block ?? null : null));
|
||||
|
||||
watch(selectedId, (id) => {
|
||||
sidebarTab.value = id ? 'block' : 'blocks';
|
||||
});
|
||||
|
||||
// ——— Aktionen am Blockbaum ———
|
||||
function select(id) {
|
||||
selectedId.value = id ?? null;
|
||||
}
|
||||
|
||||
function insert(list, index, type) {
|
||||
if (readOnly.value) return;
|
||||
|
||||
const block = createBlock(type);
|
||||
list.splice(index, 0, block);
|
||||
select(block.id);
|
||||
}
|
||||
|
||||
function insertFromPalette(type) {
|
||||
const found = selected.value ? locate(working.content.blocks, selected.value.id) : null;
|
||||
found ? insert(found.list, found.index + 1, type) : insert(working.content.blocks, working.content.blocks.length, type);
|
||||
sheetOpen.value = false;
|
||||
requestAnimationFrame(() => document.querySelector(`[data-block-id="${selectedId.value}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'center' }));
|
||||
}
|
||||
|
||||
function remove(id) {
|
||||
const found = locate(working.content.blocks, id);
|
||||
|
||||
if (!found) return;
|
||||
|
||||
found.list.splice(found.index, 1);
|
||||
|
||||
if (selectedId.value === id) select(null);
|
||||
}
|
||||
|
||||
function move(id, direction) {
|
||||
const found = locate(working.content.blocks, id);
|
||||
const target = found ? found.index + direction : -1;
|
||||
|
||||
if (found && target >= 0 && target < found.list.length) {
|
||||
found.list.splice(target, 0, found.list.splice(found.index, 1)[0]);
|
||||
}
|
||||
}
|
||||
|
||||
function duplicate(id) {
|
||||
const found = locate(working.content.blocks, id);
|
||||
|
||||
if (!found) return;
|
||||
|
||||
const copy = duplicateBlock(found.block);
|
||||
found.list.splice(found.index + 1, 0, copy);
|
||||
Object.assign(previews, { [copy.id]: previews[id] });
|
||||
select(copy.id);
|
||||
}
|
||||
|
||||
function containsActive(item) {
|
||||
const candidates = [selected.value, hoveredId.value ? locate(working.content.blocks, hoveredId.value)?.block : null].filter(Boolean);
|
||||
|
||||
return candidates.some((block) => block.items?.includes(item) || locate(item.blocks, block.id));
|
||||
}
|
||||
|
||||
// ——— Hochladen ———
|
||||
async function uploadImage(file) {
|
||||
const body = new FormData();
|
||||
body.append('image', file);
|
||||
|
||||
return http.post(`${base}/bilder`, body);
|
||||
}
|
||||
|
||||
async function uploadFile(file) {
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
const result = await http.post(`${base}/dateien`, body);
|
||||
files.value = [result.file, ...files.value];
|
||||
|
||||
return result.file;
|
||||
}
|
||||
|
||||
const peopleCache = reactive({});
|
||||
|
||||
provide('pagebuilder:editor', {
|
||||
types,
|
||||
groups: props.blockGroups,
|
||||
selectedId,
|
||||
hoveredId,
|
||||
previews,
|
||||
readOnly,
|
||||
files,
|
||||
peopleCache,
|
||||
audienceOptions: props.audienceOptions,
|
||||
select,
|
||||
insert,
|
||||
remove,
|
||||
move,
|
||||
duplicate,
|
||||
containsActive,
|
||||
uploadImage,
|
||||
uploadFile,
|
||||
imageUrl: (path) => `${props.uploadsUrl}/${path}`,
|
||||
});
|
||||
provide('pagebuilder:list', EditorBlockList);
|
||||
provide('pagebuilder:types', types);
|
||||
provide('pagebuilder:editing', computed(() => !readOnly.value));
|
||||
|
||||
// ——— Vorschau dynamischer Blöcke (Bild-URLs, Personen, aktuelle Beiträge) ———
|
||||
const previewHashes = {};
|
||||
let previewTimer;
|
||||
|
||||
function refreshPreviews() {
|
||||
const changed = [];
|
||||
|
||||
walk(working.content.blocks, (block) => {
|
||||
if (!types[block.type]?.dynamic) return;
|
||||
|
||||
const hash = JSON.stringify(block.data);
|
||||
|
||||
if (previewHashes[block.id] !== hash) {
|
||||
previewHashes[block.id] = hash;
|
||||
changed.push({ id: block.id, type: block.type, data: block.data });
|
||||
}
|
||||
});
|
||||
|
||||
if (changed.length) {
|
||||
http.post(`${base}/vorschau`, { blocks: changed.slice(0, 100) })
|
||||
.then((data) => Object.assign(previews, data.props))
|
||||
.catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
// ——— Speichern: laufend als Entwurf ———
|
||||
const saveState = ref('saved');
|
||||
const savedAt = ref(page.value.draft_updated_at);
|
||||
let saveTimer;
|
||||
let lastSaved = JSON.stringify(working);
|
||||
|
||||
function serialize() {
|
||||
return { title: working.title, content: working.content };
|
||||
}
|
||||
|
||||
async function save() {
|
||||
clearTimeout(saveTimer);
|
||||
|
||||
if (readOnly.value) return;
|
||||
|
||||
const snapshot = JSON.stringify(working);
|
||||
|
||||
if (snapshot === lastSaved) {
|
||||
saveState.value = 'saved';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
saveState.value = 'saving';
|
||||
|
||||
try {
|
||||
const data = await http.put(`${base}/entwurf`, serialize());
|
||||
lastSaved = snapshot;
|
||||
page.value = data.page;
|
||||
savedAt.value = new Date().toISOString();
|
||||
saveState.value = JSON.stringify(working) === lastSaved ? 'saved' : 'dirty';
|
||||
|
||||
if (saveState.value === 'dirty') scheduleSave();
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
saveState.value = 'error';
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleSave(delay = 1200) {
|
||||
clearTimeout(saveTimer);
|
||||
saveTimer = setTimeout(save, delay);
|
||||
}
|
||||
|
||||
function handleError(error) {
|
||||
if (error.status === 423) {
|
||||
readOnly.value = true;
|
||||
lockedBy.value = error.data.lockedBy;
|
||||
toast.error(error.message);
|
||||
} else if (error.status === 422 && error.data?.errors?.title) {
|
||||
toast.error(error.data.errors.title[0]);
|
||||
} else {
|
||||
toast.error(error.message || 'Speichern fehlgeschlagen. Bitte die Verbindung prüfen.');
|
||||
}
|
||||
}
|
||||
|
||||
// ——— Rückgängig / Wiederholen ———
|
||||
const undoStack = ref([]);
|
||||
const redoStack = ref([]);
|
||||
let historyBase = JSON.stringify(working);
|
||||
let applyingHistory = false;
|
||||
let historyTimer;
|
||||
|
||||
function recordHistory() {
|
||||
const current = JSON.stringify(working);
|
||||
|
||||
if (current !== historyBase) {
|
||||
undoStack.value = [...undoStack.value.slice(-49), historyBase];
|
||||
redoStack.value = [];
|
||||
historyBase = current;
|
||||
}
|
||||
}
|
||||
|
||||
function applySnapshot(snapshot) {
|
||||
applyingHistory = true;
|
||||
const state = JSON.parse(snapshot);
|
||||
working.title = state.title;
|
||||
working.content = state.content;
|
||||
historyBase = snapshot;
|
||||
|
||||
if (selectedId.value && !locate(working.content.blocks, selectedId.value)) select(null);
|
||||
|
||||
setTimeout(() => (applyingHistory = false));
|
||||
}
|
||||
|
||||
function undo() {
|
||||
recordHistory();
|
||||
|
||||
if (!undoStack.value.length) return;
|
||||
|
||||
redoStack.value = [...redoStack.value, JSON.stringify(working)];
|
||||
applySnapshot(undoStack.value.at(-1));
|
||||
undoStack.value = undoStack.value.slice(0, -1);
|
||||
}
|
||||
|
||||
function redo() {
|
||||
if (!redoStack.value.length) return;
|
||||
|
||||
undoStack.value = [...undoStack.value, JSON.stringify(working)];
|
||||
applySnapshot(redoStack.value.at(-1));
|
||||
redoStack.value = redoStack.value.slice(0, -1);
|
||||
}
|
||||
|
||||
watch(working, () => {
|
||||
if (readOnly.value) return;
|
||||
|
||||
saveState.value = 'dirty';
|
||||
scheduleSave();
|
||||
clearTimeout(previewTimer);
|
||||
previewTimer = setTimeout(refreshPreviews, 500);
|
||||
|
||||
if (!applyingHistory) {
|
||||
clearTimeout(historyTimer);
|
||||
historyTimer = setTimeout(recordHistory, 700);
|
||||
}
|
||||
}, { deep: true });
|
||||
|
||||
function onKeydown(event) {
|
||||
const target = event.target;
|
||||
const typing = target.closest?.('input, textarea, select, [contenteditable="true"]');
|
||||
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
|
||||
event.preventDefault();
|
||||
save();
|
||||
} else if (!typing && (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'z') {
|
||||
event.preventDefault();
|
||||
event.shiftKey ? redo() : undo();
|
||||
} else if (!typing && (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'y') {
|
||||
event.preventDefault();
|
||||
redo();
|
||||
} else if (event.key === 'Escape' && !typing) {
|
||||
select(null);
|
||||
}
|
||||
}
|
||||
|
||||
// ——— Bearbeitungssperre ———
|
||||
let lockTimer;
|
||||
|
||||
async function heartbeat(takeover = false) {
|
||||
try {
|
||||
await http.post(`${base}/sperre`, { takeover });
|
||||
|
||||
if (takeover) {
|
||||
readOnly.value = false;
|
||||
lockedBy.value = null;
|
||||
toast.success('Sie bearbeiten die Seite jetzt.');
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status === 423) {
|
||||
readOnly.value = true;
|
||||
lockedBy.value = error.data.lockedBy;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function takeOver() {
|
||||
await heartbeat(true);
|
||||
router.reload({ only: ['working', 'page'], onSuccess: () => Object.assign(working, clone(props.working)) });
|
||||
}
|
||||
|
||||
function leave() {
|
||||
if (readOnly.value) return;
|
||||
|
||||
if (JSON.stringify(working) !== lastSaved) {
|
||||
fetch(`${base}/entwurf`, {
|
||||
method: 'PUT',
|
||||
keepalive: true,
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-XSRF-TOKEN': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]*)/)?.[1] ?? '') },
|
||||
body: JSON.stringify(serialize()),
|
||||
});
|
||||
}
|
||||
|
||||
http.post(`${base}/sperre/freigeben`, {}, { keepalive: true }).catch(() => {});
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
refreshPreviews();
|
||||
window.addEventListener('keydown', onKeydown);
|
||||
window.addEventListener('pagehide', leave);
|
||||
lockTimer = setInterval(() => !readOnly.value && heartbeat(), 45_000);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('keydown', onKeydown);
|
||||
window.removeEventListener('pagehide', leave);
|
||||
clearInterval(lockTimer);
|
||||
clearTimeout(saveTimer);
|
||||
leave();
|
||||
});
|
||||
|
||||
// ——— Veröffentlichen & Co. ———
|
||||
const dialogs = reactive({ publish: false, review: false, revisions: false, settings: false, newPage: false });
|
||||
|
||||
async function publish(scheduledAt) {
|
||||
clearTimeout(saveTimer);
|
||||
|
||||
try {
|
||||
const data = await http.post(`${base}/veroeffentlichen`, { ...serialize(), scheduled_at: scheduledAt || null });
|
||||
page.value = data.page;
|
||||
lastSaved = JSON.stringify(working);
|
||||
saveState.value = 'saved';
|
||||
dialogs.publish = false;
|
||||
toast.success(scheduledAt ? `Veröffentlichung geplant für ${new Date(scheduledAt).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })}` : 'Seite veröffentlicht', {
|
||||
action: scheduledAt ? undefined : { label: 'Ansehen', onClick: () => router.visit(page.value.url) },
|
||||
});
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function requestReview(message) {
|
||||
await save();
|
||||
|
||||
try {
|
||||
const data = await http.post(`${base}/freigabe`, { message });
|
||||
dialogs.review = false;
|
||||
toast.success(`Freigabe angefordert – ${data.recipients} ${data.recipients === 1 ? 'Person wurde' : 'Personen wurden'} benachrichtigt.`);
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function simpleAction(method, url, confirmText, success) {
|
||||
if (confirmText && !window.confirm(confirmText)) return;
|
||||
|
||||
try {
|
||||
const data = await http[method](url);
|
||||
|
||||
if (data.page) page.value = data.page;
|
||||
|
||||
if (data.working) {
|
||||
applySnapshot(JSON.stringify(data.working));
|
||||
lastSaved = JSON.stringify(working);
|
||||
}
|
||||
|
||||
if (data.redirect) {
|
||||
router.visit(data.redirect);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success(success);
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function restored(data) {
|
||||
page.value = data.page;
|
||||
applySnapshot(JSON.stringify(data.working));
|
||||
lastSaved = JSON.stringify(working);
|
||||
Object.keys(previewHashes).forEach((key) => delete previewHashes[key]);
|
||||
refreshPreviews();
|
||||
dialogs.revisions = false;
|
||||
toast.success('Version als Entwurf wiederhergestellt');
|
||||
}
|
||||
|
||||
const status = computed(() => {
|
||||
if (page.value.scheduled_at) return { label: `Geplant: ${new Date(page.value.scheduled_at).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' })}`, class: 'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-200' };
|
||||
if (!page.value.is_published) return { label: 'Nicht veröffentlicht', class: 'bg-muted text-muted-foreground' };
|
||||
if (page.value.has_draft) return { label: 'Entwurf mit Änderungen', class: 'bg-brand-soft text-brand-soft-foreground' };
|
||||
|
||||
return { label: 'Veröffentlicht', class: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-200' };
|
||||
});
|
||||
|
||||
const devices = [
|
||||
{ key: 'desktop', label: 'Desktop', icon: Monitor, width: 'max-w-[1100px]' },
|
||||
{ key: 'tablet', label: 'Tablet', icon: Tablet, width: 'max-w-[768px]' },
|
||||
{ key: 'mobile', label: 'Smartphone', icon: Smartphone, width: 'max-w-[390px]' },
|
||||
];
|
||||
const canvasWidth = computed(() => devices.find((d) => d.key === device.value).width);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Head :title="`Bearbeiten: ${working.title}`" />
|
||||
|
||||
<div class="flex h-dvh flex-col bg-background">
|
||||
<!-- Kopfleiste -->
|
||||
<header class="z-30 flex h-14 shrink-0 items-center gap-2 border-b bg-card px-2 sm:px-3">
|
||||
<Link :href="page.is_published ? page.url : '/redaktion'" class="grid size-9 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground" title="Zurück">
|
||||
<ArrowLeft class="size-5" />
|
||||
</Link>
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="truncate text-sm font-semibold">{{ working.title || 'Ohne Titel' }}</span>
|
||||
<span class="hidden shrink-0 rounded px-1.5 py-0.5 text-[11px] font-medium sm:inline" :class="status.class">{{ status.label }}</span>
|
||||
</div>
|
||||
<p class="flex items-center gap-1 truncate text-xs text-muted-foreground" aria-live="polite">
|
||||
<template v-if="readOnly"><Lock class="size-3" /> Nur lesen</template>
|
||||
<template v-else-if="saveState === 'saving'"><LoaderCircle class="size-3 animate-spin" /> Speichert …</template>
|
||||
<template v-else-if="saveState === 'error'"><CloudAlert class="size-3 text-destructive" /> Nicht gespeichert</template>
|
||||
<template v-else-if="saveState === 'dirty'">Ungespeicherte Änderungen</template>
|
||||
<template v-else-if="savedAt"><CircleCheck class="size-3" /> Entwurf gespeichert {{ formatTime(savedAt) }}</template>
|
||||
<template v-else>{{ page.url }}</template>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="hidden items-center gap-0.5 md:flex">
|
||||
<button type="button" class="grid size-9 place-items-center rounded-md text-muted-foreground hover:bg-accent disabled:opacity-40" title="Rückgängig (Strg+Z)" :disabled="!undoStack.length || readOnly" @click="undo"><Undo2 class="size-4" /></button>
|
||||
<button type="button" class="grid size-9 place-items-center rounded-md text-muted-foreground hover:bg-accent disabled:opacity-40" title="Wiederholen (Strg+Y)" :disabled="!redoStack.length || readOnly" @click="redo"><Redo2 class="size-4" /></button>
|
||||
<span class="mx-1 h-6 w-px bg-border" />
|
||||
<div class="flex rounded-md border p-0.5" role="group" aria-label="Vorschau">
|
||||
<button
|
||||
v-for="d in devices"
|
||||
:key="d.key"
|
||||
type="button"
|
||||
class="grid size-8 place-items-center rounded"
|
||||
:class="device === d.key ? 'bg-brand-soft text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'"
|
||||
:title="d.label"
|
||||
:aria-pressed="device === d.key"
|
||||
@click="device = d.key"
|
||||
>
|
||||
<component :is="d.icon" class="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger class="grid size-9 place-items-center rounded-md text-muted-foreground hover:bg-accent" aria-label="Weitere Aktionen">
|
||||
<EllipsisVertical class="size-5" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" class="w-64">
|
||||
<DropdownMenuItem v-if="page.is_published" as-child><a :href="page.url" target="_blank"><Eye /> Veröffentlichte Seite ansehen</a></DropdownMenuItem>
|
||||
<DropdownMenuItem @select="dialogs.revisions = true"><History /> Versionen</DropdownMenuItem>
|
||||
<DropdownMenuItem v-if="page.can.configure" @select="dialogs.settings = true"><Settings2 /> Seiteneinstellungen</DropdownMenuItem>
|
||||
<DropdownMenuItem v-if="page.can.create_child" @select="dialogs.newPage = true"><FilePlus2 /> Unterseite anlegen</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
v-if="page.has_draft && page.is_published && !readOnly"
|
||||
@select="simpleAction('delete', `${base}/entwurf`, 'Alle Änderungen seit der letzten Veröffentlichung verwerfen?', 'Entwurf verworfen')"
|
||||
>
|
||||
<Undo2 /> Entwurf verwerfen
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem v-if="page.scheduled_at && page.can.publish" @select="simpleAction('delete', `${base}/planung`, null, 'Planung aufgehoben – der Stand ist wieder ein Entwurf')">
|
||||
<CalendarClock /> Geplante Veröffentlichung aufheben
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem v-if="page.is_published && page.can.publish" @select="simpleAction('post', `${base}/zurueckziehen`, 'Seite offline nehmen? Der Inhalt bleibt als Entwurf erhalten.', 'Seite ist offline')">
|
||||
<Lock /> Veröffentlichung zurückziehen
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem v-if="page.can.delete" class="text-destructive" @select="simpleAction('delete', base, 'Seite endgültig löschen? Versionen und Dateien werden entfernt.', 'Seite gelöscht')">
|
||||
<Trash2 /> Seite löschen
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<Button v-if="page.can.publish" :disabled="readOnly" @click="dialogs.publish = true">
|
||||
<Send /> <span class="hidden sm:inline">Veröffentlichen</span>
|
||||
</Button>
|
||||
<Button v-else :disabled="readOnly" @click="dialogs.review = true">
|
||||
<Send /> <span class="hidden sm:inline">Freigabe anfordern</span>
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<div v-if="readOnly" class="flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-amber-200 bg-amber-50 px-4 py-2.5 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950/50 dark:text-amber-100">
|
||||
<Lock class="size-4 shrink-0" />
|
||||
<span class="flex-1">{{ lockedBy?.name ?? 'Jemand anderes' }} bearbeitet diese Seite gerade. Sie sehen den zuletzt gespeicherten Stand.</span>
|
||||
<Button size="sm" variant="outline" class="bg-card" @click="takeOver">Bearbeitung übernehmen</Button>
|
||||
</div>
|
||||
|
||||
<div class="flex min-h-0 flex-1">
|
||||
<!-- Arbeitsfläche -->
|
||||
<main class="min-w-0 flex-1 overflow-y-auto" @click="select(null)">
|
||||
<div class="mx-auto px-4 py-8 transition-[max-width] duration-300 sm:px-8" :class="canvasWidth">
|
||||
<nav v-if="breadcrumbs.length" class="mb-2 flex flex-wrap gap-1 text-xs text-muted-foreground" aria-label="Brotkrumen">
|
||||
<span v-for="crumb in breadcrumbs" :key="crumb.url">{{ crumb.title }} /</span>
|
||||
</nav>
|
||||
<input
|
||||
v-model="working.title"
|
||||
class="mb-6 w-full bg-transparent text-3xl font-semibold tracking-tight outline-none placeholder:text-muted-foreground/60"
|
||||
placeholder="Titel der Seite"
|
||||
maxlength="200"
|
||||
aria-label="Titel der Seite"
|
||||
:readonly="readOnly"
|
||||
@click.stop
|
||||
/>
|
||||
<div class="@container">
|
||||
<EditorBlockList :item="working.content" root />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Seitenleiste -->
|
||||
<aside class="hidden w-[340px] shrink-0 flex-col border-l bg-card lg:flex">
|
||||
<div class="flex shrink-0 border-b px-2" role="tablist">
|
||||
<button
|
||||
v-for="tab in [{ key: 'blocks', label: 'Blöcke' }, { key: 'block', label: 'Ausgewählter Block' }]"
|
||||
:key="tab.key"
|
||||
type="button"
|
||||
role="tab"
|
||||
class="relative px-3 py-3 text-sm font-medium disabled:opacity-40"
|
||||
:class="sidebarTab === tab.key ? 'text-foreground' : 'text-muted-foreground hover:text-foreground'"
|
||||
:aria-selected="sidebarTab === tab.key"
|
||||
:disabled="tab.key === 'block' && !selected"
|
||||
@click="sidebarTab = tab.key"
|
||||
>
|
||||
{{ tab.label }}
|
||||
<span v-if="sidebarTab === tab.key" class="absolute inset-x-2 bottom-0 h-[3px] rounded-t-full bg-brand" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-4">
|
||||
<BlockSettings v-if="sidebarTab === 'block' && selected" :key="selected.id" :block="selected" />
|
||||
<template v-else>
|
||||
<p class="mb-4 text-xs text-muted-foreground">Klicken fügt den Block unter dem ausgewählten ein. Blöcke lassen sich auch an jede Stelle ziehen.</p>
|
||||
<BlockPalette @pick="insertFromPalette" />
|
||||
</template>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<!-- Kleine Bildschirme: Seitenleiste als Blatt -->
|
||||
<div class="fixed right-4 bottom-4 z-30 flex gap-2 lg:hidden">
|
||||
<Button variant="outline" class="bg-card shadow-md" :disabled="readOnly" @click="sidebarTab = 'blocks'; sheetOpen = true">Block hinzufügen</Button>
|
||||
<Button v-if="selected" class="shadow-md" @click="sidebarTab = 'block'; sheetOpen = true">Einstellungen</Button>
|
||||
</div>
|
||||
<Sheet v-model:open="sheetOpen">
|
||||
<SheetContent side="right" class="w-[340px] overflow-y-auto p-4 sm:max-w-[340px]">
|
||||
<SheetHeader class="p-0"><SheetTitle>{{ sidebarTab === 'block' ? 'Block' : 'Blöcke' }}</SheetTitle></SheetHeader>
|
||||
<BlockSettings v-if="sidebarTab === 'block' && selected" :key="selected.id" :block="selected" />
|
||||
<BlockPalette v-else @pick="insertFromPalette" />
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
<PublishDialog v-model:open="dialogs.publish" :scheduled-at="page.scheduled_at" @publish="publish" />
|
||||
<ReviewDialog v-model:open="dialogs.review" @submit="requestReview" />
|
||||
<RevisionsDialog v-model:open="dialogs.revisions" :base="base" :read-only="readOnly" @restored="restored" />
|
||||
<PageSettingsDialog v-model:open="dialogs.settings" :page="page" :base="base" @saved="(data) => (page = data.page)" />
|
||||
<NewPageDialog v-model:open="dialogs.newPage" :parent-id="page.id" :parent-title="page.title" @before-create="save" />
|
||||
</div>
|
||||
|
||||
<Toaster position="bottom-left" />
|
||||
</template>
|
||||
55
plugins-core/pages/resources/js/pages/Index.vue
Normal file
55
plugins-core/pages/resources/js/pages/Index.vue
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<script setup>
|
||||
import { ref } from 'vue';
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { ChevronRight, FileText, FolderOpen, Plus } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import EmptyState from '@/components/EmptyState.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import NewPageDialog from '../components/NewPageDialog.vue';
|
||||
|
||||
defineProps({
|
||||
tree: { type: Array, required: true },
|
||||
canCreate: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const creating = ref(false);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout title="Seiten">
|
||||
<div class="mb-6 flex flex-wrap items-end justify-between gap-4">
|
||||
<div>
|
||||
<h1 class="text-2xl font-semibold tracking-tight">Seiten</h1>
|
||||
<p class="mt-1 text-sm text-muted-foreground">Informationen der Bereiche, Abteilungen und Gremien.</p>
|
||||
</div>
|
||||
<Button v-if="canCreate" @click="creating = true"><Plus /> Neue Seite</Button>
|
||||
</div>
|
||||
|
||||
<div v-if="tree.length" class="grid gap-5 md:grid-cols-2 xl:grid-cols-3">
|
||||
<section v-for="section in tree" :key="section.id" class="rounded-lg border bg-card">
|
||||
<Link :href="section.url" class="flex items-center gap-3 border-b px-5 py-4 hover:bg-accent/50">
|
||||
<span class="grid size-10 shrink-0 place-items-center rounded-lg bg-brand-soft text-brand-text">
|
||||
<FolderOpen v-if="section.children.length" class="size-5" />
|
||||
<FileText v-else class="size-5" />
|
||||
</span>
|
||||
<span class="min-w-0 flex-1 truncate font-semibold">{{ section.title }}</span>
|
||||
<ChevronRight class="size-4 text-muted-foreground" />
|
||||
</Link>
|
||||
<ul v-if="section.children.length" class="grid p-2">
|
||||
<li v-for="child in section.children.slice(0, 8)" :key="child.id">
|
||||
<Link :href="child.url" class="flex items-center justify-between rounded-md px-3 py-2 text-sm hover:bg-accent">
|
||||
<span class="truncate">{{ child.title }}</span>
|
||||
<span v-if="child.children.length" class="text-xs text-muted-foreground">{{ child.children.length }}</span>
|
||||
</Link>
|
||||
</li>
|
||||
<li v-if="section.children.length > 8" class="px-3 py-1.5 text-[13px]">
|
||||
<Link :href="section.url" class="font-medium text-brand-text hover:underline">Alle {{ section.children.length }} Seiten</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
<div v-else class="rounded-lg border bg-card"><EmptyState :icon="FileText" title="Noch keine Seiten" text="Hier erscheinen Seiten, sobald sie veröffentlicht sind." /></div>
|
||||
|
||||
<NewPageDialog v-model:open="creating" />
|
||||
</AppLayout>
|
||||
</template>
|
||||
72
plugins-core/pages/resources/js/pages/Show.vue
Normal file
72
plugins-core/pages/resources/js/pages/Show.vue
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { ChevronRight, CalendarClock, PencilLine } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import PageContent from '@/pagebuilder/PageContent.vue';
|
||||
import { formatDate } from '@/lib/format';
|
||||
import PageTreeNav from '../components/PageTreeNav.vue';
|
||||
|
||||
const props = defineProps({
|
||||
page: { type: Object, required: true },
|
||||
content: { type: Object, required: true },
|
||||
breadcrumbs: { type: Array, default: () => [] },
|
||||
section: { type: Object, required: true },
|
||||
editor: { type: Object, default: null },
|
||||
});
|
||||
|
||||
const hasSectionNav = props.section.children.length > 0;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout :title="page.title">
|
||||
<div class="grid gap-8" :class="hasSectionNav ? 'lg:grid-cols-[260px_minmax(0,1fr)]' : ''">
|
||||
<aside v-if="hasSectionNav" class="hidden lg:block">
|
||||
<nav class="sticky top-24 rounded-lg border bg-card p-2" aria-label="Seiten in diesem Bereich">
|
||||
<Link
|
||||
:href="section.url"
|
||||
class="block rounded-md px-3 py-2 text-sm font-semibold"
|
||||
:class="section.active ? 'bg-brand-soft text-brand-soft-foreground' : 'hover:bg-accent'"
|
||||
>
|
||||
{{ section.title }}
|
||||
</Link>
|
||||
<PageTreeNav :items="section.children" :current="page.url" />
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
<article class="min-w-0" :class="hasSectionNav ? '' : 'mx-auto w-full max-w-5xl'">
|
||||
<nav v-if="breadcrumbs.length" class="mb-3 flex flex-wrap items-center gap-1 text-[13px] text-muted-foreground" aria-label="Brotkrumen">
|
||||
<template v-for="crumb in breadcrumbs" :key="crumb.url">
|
||||
<Link :href="crumb.url" class="hover:text-foreground hover:underline">{{ crumb.title }}</Link>
|
||||
<ChevronRight class="size-3.5" />
|
||||
</template>
|
||||
<span class="text-foreground">{{ page.title }}</span>
|
||||
</nav>
|
||||
|
||||
<header class="mb-8 flex flex-wrap items-start justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<h1 class="text-3xl leading-tight font-semibold tracking-tight">{{ page.title }}</h1>
|
||||
<p v-if="page.published_at" class="mt-1.5 text-[13px] text-muted-foreground">Zuletzt aktualisiert am {{ formatDate(page.published_at) }}</p>
|
||||
</div>
|
||||
<Button v-if="editor" variant="outline" as-child>
|
||||
<Link :href="editor.url"><PencilLine /> Bearbeiten</Link>
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<div v-if="editor && (!page.is_published || editor.has_draft || editor.scheduled_at)" class="mb-6 flex items-start gap-3 rounded-lg border border-brand-200 bg-brand-soft px-4 py-3 text-sm">
|
||||
<CalendarClock v-if="editor.scheduled_at" class="mt-0.5 size-4 shrink-0 text-brand-text" />
|
||||
<PencilLine v-else class="mt-0.5 size-4 shrink-0 text-brand-text" />
|
||||
<p>
|
||||
<template v-if="!page.is_published">Diese Seite ist noch nicht veröffentlicht. Nur Redakteure sehen sie.</template>
|
||||
<template v-else-if="editor.scheduled_at">Eine neue Fassung wird am {{ new Date(editor.scheduled_at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' }) }} veröffentlicht.</template>
|
||||
<template v-else>Es gibt unveröffentlichte Änderungen an dieser Seite.</template>
|
||||
<Link :href="editor.url" class="ml-1 font-medium text-brand-text hover:underline">Im Editor öffnen</Link>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<PageContent :content="content" />
|
||||
<p v-if="!content.blocks.length" class="rounded-lg border border-dashed px-6 py-12 text-center text-sm text-muted-foreground">Diese Seite hat noch keinen Inhalt.</p>
|
||||
</article>
|
||||
</div>
|
||||
</AppLayout>
|
||||
</template>
|
||||
32
plugins-core/pages/routes/web.php
Normal file
32
plugins-core/pages/routes/web.php
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Inhaus\Plugins\Pages\Http\Controllers\PageController;
|
||||
use Inhaus\Plugins\Pages\Http\Controllers\PageEditorController;
|
||||
|
||||
Route::middleware('auth')->group(function () {
|
||||
Route::get('/seiten', [PageController::class, 'index'])->name('pages.index');
|
||||
Route::get('/seiten/{path}', [PageController::class, 'show'])->where('path', '[a-z0-9][a-z0-9\-/]*')->name('pages.show');
|
||||
Route::get('/dateien/seiten/{file}/{name}', [PageController::class, 'file'])->name('pages.file');
|
||||
|
||||
Route::prefix('redaktion/seiten')->name('pages.')->controller(PageEditorController::class)->group(function () {
|
||||
Route::post('/', 'store')->name('store');
|
||||
Route::get('/{page}', 'edit')->name('editor');
|
||||
Route::put('/{page}/entwurf', 'saveDraft')->name('draft');
|
||||
Route::delete('/{page}/entwurf', 'discardDraft')->name('draft.discard');
|
||||
Route::post('/{page}/veroeffentlichen', 'publish')->name('publish');
|
||||
Route::post('/{page}/freigabe', 'requestReview')->name('review');
|
||||
Route::delete('/{page}/planung', 'cancelSchedule')->name('schedule.cancel');
|
||||
Route::post('/{page}/zurueckziehen', 'unpublish')->name('unpublish');
|
||||
Route::put('/{page}/einstellungen', 'settings')->name('settings');
|
||||
Route::delete('/{page}', 'destroy')->name('destroy');
|
||||
Route::get('/{page}/versionen', 'revisions')->name('revisions');
|
||||
Route::get('/{page}/versionen/{revision}', 'revision')->name('revision');
|
||||
Route::post('/{page}/versionen/{revision}/wiederherstellen', 'restore')->name('restore');
|
||||
Route::post('/{page}/sperre', 'lock')->name('lock');
|
||||
Route::post('/{page}/sperre/freigeben', 'unlock')->name('unlock');
|
||||
Route::post('/{page}/bilder', 'uploadImage')->name('images');
|
||||
Route::post('/{page}/dateien', 'uploadFile')->name('files');
|
||||
Route::post('/{page}/vorschau', 'preview')->name('preview');
|
||||
});
|
||||
});
|
||||
49
plugins-core/pages/src/EditorialPages.php
Normal file
49
plugins-core/pages/src/EditorialPages.php
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages;
|
||||
|
||||
use App\Models\User;
|
||||
use Inhaus\Plugins\Pages\Models\Page;
|
||||
|
||||
/**
|
||||
* „Redaktion → Seiten“: Seiten, die die Person bearbeiten darf, mit Status.
|
||||
*/
|
||||
final class EditorialPages
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function props(User $user): array
|
||||
{
|
||||
$ids = $user->can('pages.manage') ? true : $user->permissions()->ids('pages.edit', 'page');
|
||||
$tree = app(PageTree::class);
|
||||
$options = $tree->options();
|
||||
|
||||
$pages = Page::query()
|
||||
->when($ids !== true, fn ($q) => $q->whereIn('id', $ids))
|
||||
->with('lockedBy:id,name')
|
||||
->get(['id', 'parent_id', 'title', 'path', 'published_at', 'draft_updated_at', 'scheduled_at', 'locked_by', 'locked_until', 'updated_at'])
|
||||
->sortBy(fn (Page $page) => array_search($page->id, array_keys($options), true))
|
||||
->values();
|
||||
|
||||
return [
|
||||
'pages' => $pages->map(fn (Page $page) => [
|
||||
'id' => $page->id,
|
||||
'title' => $page->title,
|
||||
'depth' => substr_count($page->path, '/'),
|
||||
'url' => $page->url(),
|
||||
'edit_url' => route('pages.editor', $page),
|
||||
'status' => match (true) {
|
||||
$page->scheduled_at !== null => 'scheduled',
|
||||
$page->draft_updated_at !== null => 'draft',
|
||||
$page->published_at !== null => 'published',
|
||||
default => 'new',
|
||||
},
|
||||
'scheduled_at' => $page->scheduled_at?->toIso8601String(),
|
||||
'changed_at' => ($page->draft_updated_at ?? $page->published_at ?? $page->updated_at)?->toIso8601String(),
|
||||
'locked_by' => $page->isLockedFor($user) ? $page->lockedBy?->name : null,
|
||||
])->all(),
|
||||
'canCreate' => $user->can('pages.manage'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages\Filament\Resources\ContentPages;
|
||||
|
||||
use App\Filament\Components\AudienceSection;
|
||||
use App\Filament\Components\RoleGrantSelect;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages\CreateContentPage;
|
||||
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages\EditContentPage;
|
||||
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages\ListContentPages;
|
||||
use Inhaus\Plugins\Pages\Models\Page;
|
||||
use Inhaus\Plugins\Pages\PageTree;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Seitenbaum im Admin: Struktur, Adressen, Sichtbarkeit und Rechte.
|
||||
* Der Inhalt wird im Portal mit dem Pagebuilder bearbeitet.
|
||||
*/
|
||||
class ContentPageResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Page::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedDocumentText;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
|
||||
protected static ?int $navigationSort = 0;
|
||||
|
||||
protected static ?string $modelLabel = 'Seite';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Seiten';
|
||||
|
||||
protected static ?string $slug = 'seiten';
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'title';
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(3)
|
||||
->components([
|
||||
Section::make('Seite')
|
||||
->columnSpan(2)
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('title')->label('Titel')->required()->maxLength(200)->columnSpanFull(),
|
||||
Select::make('parent_id')
|
||||
->label('Übergeordnete Seite')
|
||||
->placeholder('– oberste Ebene –')
|
||||
->options(fn (?Page $record) => collect(app(PageTree::class)->options())
|
||||
->except($record ? [$record->id, ...app(PageTree::class)->descendantIds([$record->id])] : [])
|
||||
->all())
|
||||
->searchable()
|
||||
->required(fn () => ! auth()->user()->can('pages.manage'))
|
||||
->live(),
|
||||
TextInput::make('slug')
|
||||
->label('Kürzel in der Adresse')
|
||||
->helperText('Leer lassen = aus dem Titel. Ändert auch die Adressen der Unterseiten.')
|
||||
->maxLength(120)
|
||||
->regex('/^[a-z0-9]+(-[a-z0-9]+)*$/')
|
||||
->validationMessages(['regex' => 'Nur Kleinbuchstaben, Ziffern und Bindestriche.']),
|
||||
TextInput::make('sort')->label('Reihenfolge')->numeric()->default(0),
|
||||
Toggle::make('in_navigation')
|
||||
->label('In der Hauptnavigation anzeigen')
|
||||
->visible(fn (Get $get) => blank($get('parent_id')))
|
||||
->inline(false),
|
||||
]),
|
||||
Section::make('Status')
|
||||
->columnSpan(1)
|
||||
->schema([
|
||||
TextInput::make('status_display')
|
||||
->label('Status')
|
||||
->disabled()
|
||||
->dehydrated(false)
|
||||
->formatStateUsing(fn (?Page $record) => match (true) {
|
||||
$record === null => 'Neu',
|
||||
$record->scheduled_at !== null => 'Geplant für '.$record->scheduled_at->format('d.m.Y H:i'),
|
||||
$record->isPublished() && $record->hasDraft() => 'Veröffentlicht, mit Entwurf',
|
||||
$record->isPublished() => 'Veröffentlicht',
|
||||
default => 'Entwurf',
|
||||
}),
|
||||
])
|
||||
->visibleOn('edit'),
|
||||
Section::make('Redaktion')
|
||||
->description('Rollen, die diese Seite und alle Unterseiten bearbeiten bzw. veröffentlichen dürfen – z. B. die MAV ihre Seite „MAV“.')
|
||||
->columnSpanFull()
|
||||
->columns(2)
|
||||
->visible(fn () => auth()->user()->can('roles.manage') || auth()->user()->can('pages.manage'))
|
||||
->schema([
|
||||
RoleGrantSelect::make('editors', 'Dürfen bearbeiten', 'pages.edit', 'page', includeChildren: true),
|
||||
RoleGrantSelect::make('publishers', 'Dürfen veröffentlichen', 'pages.publish', 'page', includeChildren: true),
|
||||
]),
|
||||
AudienceSection::make('page', 'Wer die Seite sieht. Leer lassen = alle. Gilt auch für alle Unterseiten.')->columnSpanFull(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Redakteure sehen nur Seiten, die sie bearbeiten dürfen.
|
||||
*/
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
$user = auth()->user();
|
||||
$ids = $user?->can('pages.manage') ? true : ($user?->permissions()->ids('pages.edit', 'page') ?? []);
|
||||
|
||||
return parent::getEloquentQuery()->when($ids !== true, fn (Builder $q) => $q->whereIn('id', $ids));
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('path')
|
||||
->paginated([50, 100, 'all'])
|
||||
->columns([
|
||||
TextColumn::make('title')
|
||||
->label('Titel')
|
||||
->searchable()
|
||||
->weight('medium')
|
||||
->formatStateUsing(fn (string $state, Page $record) => str_repeat('— ', substr_count($record->path, '/')).$state),
|
||||
TextColumn::make('path')->label('Adresse')->formatStateUsing(fn (string $state) => '/seiten/'.$state)->color('gray')->searchable(),
|
||||
TextColumn::make('status')
|
||||
->label('Status')
|
||||
->badge()
|
||||
->state(fn (Page $record) => match (true) {
|
||||
$record->scheduled_at !== null => 'Geplant',
|
||||
$record->isPublished() && $record->hasDraft() => 'Entwurf',
|
||||
$record->isPublished() => 'Veröffentlicht',
|
||||
default => 'Neu',
|
||||
})
|
||||
->color(fn (string $state) => match ($state) {
|
||||
'Veröffentlicht' => 'success',
|
||||
'Geplant', 'Entwurf' => 'warning',
|
||||
default => 'gray',
|
||||
}),
|
||||
TextColumn::make('updated_at')->label('Geändert')->dateTime('d.m.Y H:i')->sortable(),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('content')
|
||||
->label('Inhalt bearbeiten')
|
||||
->icon(Heroicon::OutlinedPencilSquare)
|
||||
->iconButton()
|
||||
->tooltip('Inhalt bearbeiten')
|
||||
->url(fn (Page $record) => route('pages.editor', $record)),
|
||||
EditAction::make()->label('Einstellungen')->iconButton()->tooltip('Einstellungen')->icon(Heroicon::OutlinedCog6Tooth),
|
||||
DeleteAction::make()
|
||||
->iconButton()
|
||||
->tooltip('Löschen')
|
||||
->visible(fn (Page $record) => ! $record->children()->exists())
|
||||
->before(fn (Page $record) => $record->files->each->delete()),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListContentPages::route('/'),
|
||||
'create' => CreateContentPage::route('/neu'),
|
||||
'edit' => EditContentPage::route('/{record}/bearbeiten'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages;
|
||||
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\ContentPageResource;
|
||||
use Inhaus\Plugins\Pages\Models\Page;
|
||||
use Inhaus\Plugins\Pages\PageTree;
|
||||
|
||||
class CreateContentPage extends CreateRecord
|
||||
{
|
||||
protected static string $resource = ContentPageResource::class;
|
||||
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
$parent = filled($data['parent_id'] ?? null) ? Page::query()->find($data['parent_id']) : null;
|
||||
abort_unless(auth()->user()->can('create', [Page::class, $parent]), 403);
|
||||
|
||||
return [...$data, 'created_by' => auth()->id(), 'in_navigation' => $parent ? false : ($data['in_navigation'] ?? false)];
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
PageTree::flush(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nach dem Anlegen direkt in den Pagebuilder.
|
||||
*/
|
||||
protected function getRedirectUrl(): string
|
||||
{
|
||||
return route('pages.editor', $this->record);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages;
|
||||
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\ContentPageResource;
|
||||
use Inhaus\Plugins\Pages\Models\Page;
|
||||
use Inhaus\Plugins\Pages\PageTree;
|
||||
|
||||
class EditContentPage extends EditRecord
|
||||
{
|
||||
protected static string $resource = ContentPageResource::class;
|
||||
|
||||
protected function authorizeAccess(): void
|
||||
{
|
||||
abort_unless(auth()->user()->can('configure', $this->record), 403);
|
||||
}
|
||||
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
$parent = filled($data['parent_id'] ?? null) ? Page::query()->find($data['parent_id']) : null;
|
||||
|
||||
// Verschieben: an das neue Ziel muss man Seiten anlegen dürfen.
|
||||
if (($data['parent_id'] ?? null) != $this->record->parent_id) {
|
||||
abort_unless(auth()->user()->can('create', [Page::class, $parent]), 403);
|
||||
}
|
||||
|
||||
if ($parent || ! auth()->user()->can('pages.manage')) {
|
||||
$data['in_navigation'] = $parent ? false : $this->record->in_navigation;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
// Sichtbarkeit und Rechte können sich geändert haben.
|
||||
PageTree::flush(true);
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('content')->label('Inhalt bearbeiten')->icon(Heroicon::OutlinedPencilSquare)
|
||||
->url(fn () => route('pages.editor', $this->record)),
|
||||
Action::make('view')->label('Ansehen')->icon(Heroicon::OutlinedEye)->color('gray')
|
||||
->url(fn () => $this->record->url())->openUrlInNewTab(),
|
||||
DeleteAction::make()
|
||||
->visible(fn () => ! $this->record->children()->exists() && auth()->user()->can('delete', $this->record))
|
||||
->before(fn () => $this->record->files->each->delete()),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages;
|
||||
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\ContentPageResource;
|
||||
|
||||
class ListContentPages extends ListRecords
|
||||
{
|
||||
protected static string $resource = ContentPageResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [CreateAction::make()->label('Seite anlegen')];
|
||||
}
|
||||
}
|
||||
73
plugins-core/pages/src/Http/Controllers/PageController.php
Normal file
73
plugins-core/pages/src/Http/Controllers/PageController.php
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Pagebuilder\Content;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Inhaus\Plugins\Pages\Models\Page;
|
||||
use Inhaus\Plugins\Pages\Models\PageFile;
|
||||
use Inhaus\Plugins\Pages\PageTree;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class PageController extends Controller
|
||||
{
|
||||
public function index(Request $request, PageTree $tree): Response
|
||||
{
|
||||
return Inertia::render('pages::Index', [
|
||||
'tree' => $tree->visibleTree(null, $request->user()),
|
||||
'canCreate' => $request->user()->can('pages.manage'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(Request $request, string $path, PageTree $tree, Content $content): Response
|
||||
{
|
||||
$page = Page::query()->where('path', trim($path, '/'))->firstOrFail();
|
||||
$page->publishIfDue();
|
||||
|
||||
$user = $request->user();
|
||||
$canEdit = $user->can('update', $page);
|
||||
abort_unless($tree->isVisible($page->id, $user) || $canEdit, 404);
|
||||
|
||||
$ancestors = $tree->ancestors($page->id);
|
||||
$root = $ancestors[0]['id'] ?? $page->id;
|
||||
|
||||
return Inertia::render('pages::Show', [
|
||||
'page' => [
|
||||
'id' => $page->id,
|
||||
'title' => $page->title,
|
||||
'url' => $page->url(),
|
||||
'published_at' => $page->published_at?->toIso8601String(),
|
||||
'is_published' => $page->isPublished(),
|
||||
],
|
||||
'content' => $content->render($page->content, $user, ['page_id' => $page->id]),
|
||||
'breadcrumbs' => array_map(fn (array $a) => ['title' => $a['title'], 'url' => '/seiten/'.$a['path']], $ancestors),
|
||||
'section' => [
|
||||
'title' => $tree->get($root)['title'] ?? $page->title,
|
||||
'url' => '/seiten/'.($tree->get($root)['path'] ?? $page->path),
|
||||
'active' => $root === $page->id,
|
||||
'children' => $tree->visibleTree($root, $user),
|
||||
],
|
||||
'editor' => $canEdit ? [
|
||||
'url' => route('pages.editor', $page),
|
||||
'has_draft' => $page->hasDraft(),
|
||||
'scheduled_at' => $page->scheduled_at?->toIso8601String(),
|
||||
] : null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function file(Request $request, PageFile $file, PageTree $tree): StreamedResponse
|
||||
{
|
||||
$page = $file->page;
|
||||
abort_unless($tree->isVisible($page->id, $request->user()) || $request->user()->can('update', $page), 404);
|
||||
|
||||
return Storage::disk(PageFile::DISK)->download($file->path, $file->name, [
|
||||
'Content-Type' => $file->mime ?: 'application/octet-stream',
|
||||
'Cache-Control' => 'private, max-age=3600',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
]);
|
||||
}
|
||||
}
|
||||
432
plugins-core/pages/src/Http/Controllers/PageEditorController.php
Normal file
432
plugins-core/pages/src/Http/Controllers/PageEditorController.php
Normal file
|
|
@ -0,0 +1,432 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Notifications\PortalNotification;
|
||||
use App\Pagebuilder\Blocks;
|
||||
use App\Pagebuilder\Content;
|
||||
use App\Support\Audit;
|
||||
use App\Support\Images;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\File;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Inhaus\Plugins\Pages\Models\Page;
|
||||
use Inhaus\Plugins\Pages\Models\PageFile;
|
||||
use Inhaus\Plugins\Pages\Models\PageRevision;
|
||||
use Inhaus\Plugins\Pages\PageTree;
|
||||
use Inhaus\Plugins\Pages\Publishers;
|
||||
|
||||
/**
|
||||
* Pagebuilder im Portal. Speichert laufend einen Entwurf; veröffentlicht wird
|
||||
* erst ausdrücklich (oder zeitgesteuert). Wer nicht veröffentlichen darf,
|
||||
* fordert eine Freigabe an.
|
||||
*/
|
||||
class PageEditorController extends Controller
|
||||
{
|
||||
/** Dateiendungen, die nie als Download angenommen werden. */
|
||||
private const BLOCKED_EXTENSIONS = ['php', 'phtml', 'phar', 'php3', 'php4', 'php5', 'php7', 'php8', 'pht', 'shtml', 'htaccess', 'exe', 'bat', 'cmd', 'com', 'sh', 'js', 'mjs', 'html', 'htm', 'svg', 'xhtml', 'jsp', 'asp', 'aspx', 'cgi', 'pl', 'py'];
|
||||
|
||||
public function __construct(private readonly Content $content) {}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'title' => ['required', 'string', 'max:200'],
|
||||
'parent_id' => ['nullable', 'integer', Rule::exists('pages', 'id')],
|
||||
]);
|
||||
|
||||
$parent = isset($data['parent_id']) ? Page::query()->findOrFail($data['parent_id']) : null;
|
||||
Gate::authorize('create', [Page::class, $parent]);
|
||||
|
||||
$page = Page::query()->create([
|
||||
'parent_id' => $parent?->id,
|
||||
'title' => $data['title'],
|
||||
'sort' => $parent ? (int) $parent->children()->max('sort') + 1 : (int) Page::query()->whereNull('parent_id')->max('sort') + 1,
|
||||
'created_by' => $request->user()->id,
|
||||
]);
|
||||
|
||||
Audit::log('page.created', ['page' => $page->id, 'title' => $page->title]);
|
||||
|
||||
return to_route('pages.editor', $page);
|
||||
}
|
||||
|
||||
public function edit(Request $request, Page $page, Blocks $blocks, PageTree $tree): Response
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
$user = $request->user();
|
||||
$lockedBy = $page->isLockedFor($user) ? $page->lockedBy : null;
|
||||
|
||||
if (! $lockedBy) {
|
||||
$page->lockFor($user);
|
||||
}
|
||||
|
||||
return Inertia::render('pages::Editor', [
|
||||
'page' => $this->pageState($page, $user),
|
||||
'working' => $page->workingCopy(),
|
||||
'lockedBy' => $lockedBy ? ['id' => $lockedBy->id, 'name' => $lockedBy->name] : null,
|
||||
'blockTypes' => $blocks->forEditor(),
|
||||
'blockGroups' => Blocks::GROUPS,
|
||||
'files' => $page->files()->latest()->get()->map->toBlockArray(),
|
||||
'audienceOptions' => $this->audienceOptions(),
|
||||
'breadcrumbs' => array_map(fn (array $a) => ['title' => $a['title'], 'url' => '/seiten/'.$a['path']], $tree->ancestors($page->id)),
|
||||
'uploadsUrl' => rtrim(Storage::disk('uploads')->url(''), '/'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function saveDraft(Request $request, Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
|
||||
if ($response = $this->lockConflict($request, $page)) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
[$title, $content] = $this->validatedWorkingCopy($request);
|
||||
|
||||
// Stimmt der Stand mit dem veröffentlichten überein, gibt es keinen Entwurf.
|
||||
$unchanged = $page->isPublished() && $title === $page->title && $content === $page->content;
|
||||
|
||||
$page->forceFill([
|
||||
'draft_title' => $unchanged ? null : $title,
|
||||
'draft' => $unchanged ? null : $content,
|
||||
'draft_updated_at' => $unchanged ? null : now(),
|
||||
'draft_updated_by' => $unchanged ? null : $request->user()->id,
|
||||
])->save();
|
||||
|
||||
$page->lockFor($request->user());
|
||||
|
||||
return response()->json(['page' => $this->pageState($page, $request->user())]);
|
||||
}
|
||||
|
||||
public function discardDraft(Request $request, Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
|
||||
if ($response = $this->lockConflict($request, $page)) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$page->forceFill(['draft' => null, 'draft_title' => null, 'draft_updated_at' => null, 'draft_updated_by' => null])->save();
|
||||
|
||||
return response()->json(['page' => $this->pageState($page, $request->user()), 'working' => $page->workingCopy()]);
|
||||
}
|
||||
|
||||
public function publish(Request $request, Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('publish', $page);
|
||||
|
||||
if ($response = $this->lockConflict($request, $page)) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
[$title, $content] = $this->validatedWorkingCopy($request);
|
||||
$request->validate(['scheduled_at' => ['nullable', 'date', 'after:now']]);
|
||||
|
||||
if ($request->filled('scheduled_at')) {
|
||||
$at = Carbon::parse($request->input('scheduled_at'));
|
||||
$page->schedule($title, $content, $at, $request->user());
|
||||
Audit::log('page.scheduled', ['page' => $page->id, 'title' => $title, 'at' => $at->toIso8601String()]);
|
||||
} else {
|
||||
$page->publish($title, $content, $request->user());
|
||||
Audit::log('page.published', ['page' => $page->id, 'title' => $title]);
|
||||
}
|
||||
|
||||
return response()->json(['page' => $this->pageState($page->fresh(), $request->user())]);
|
||||
}
|
||||
|
||||
public function requestReview(Request $request, Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
$request->validate(['message' => ['nullable', 'string', 'max:1000']]);
|
||||
|
||||
$recipients = Publishers::for($page, $request->user());
|
||||
|
||||
if ($recipients->isEmpty()) {
|
||||
return response()->json(['message' => 'Für diese Seite ist niemand zum Veröffentlichen berechtigt. Bitte wenden Sie sich an die Administration.'], 422);
|
||||
}
|
||||
|
||||
// Höchstens eine Anfrage je Seite und Person in 10 Minuten.
|
||||
if (! Cache::add('pages.review.'.$page->id.'.'.$request->user()->id, true, 600)) {
|
||||
return response()->json(['message' => 'Die Freigabe wurde gerade erst angefordert.'], 429);
|
||||
}
|
||||
|
||||
Notification::send($recipients, new PortalNotification(
|
||||
'Freigabe angefordert: '.($page->draft_title ?? $page->title),
|
||||
trim($request->user()->name.' bittet um Veröffentlichung. '.$request->input('message', '')),
|
||||
route('pages.editor', $page),
|
||||
'file-check',
|
||||
));
|
||||
|
||||
Audit::log('page.review_requested', ['page' => $page->id]);
|
||||
|
||||
return response()->json(['recipients' => $recipients->count()]);
|
||||
}
|
||||
|
||||
public function cancelSchedule(Request $request, Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('publish', $page);
|
||||
|
||||
// Der geplante Stand wird wieder zum Entwurf – nichts geht verloren.
|
||||
$page->forceFill([
|
||||
'draft' => $page->scheduled_content,
|
||||
'draft_title' => $page->scheduled_title,
|
||||
'draft_updated_at' => now(),
|
||||
'draft_updated_by' => $request->user()->id,
|
||||
]);
|
||||
$page->cancelSchedule();
|
||||
|
||||
return response()->json(['page' => $this->pageState($page, $request->user()), 'working' => $page->workingCopy()]);
|
||||
}
|
||||
|
||||
public function unpublish(Request $request, Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('publish', $page);
|
||||
|
||||
$page->forceFill([
|
||||
'draft' => $page->draft ?? $page->content,
|
||||
'draft_title' => $page->draft_title ?? $page->title,
|
||||
'draft_updated_at' => now(),
|
||||
'content' => null,
|
||||
'published_at' => null,
|
||||
])->save();
|
||||
|
||||
Audit::log('page.unpublished', ['page' => $page->id, 'title' => $page->title]);
|
||||
|
||||
return response()->json(['page' => $this->pageState($page, $request->user())]);
|
||||
}
|
||||
|
||||
public function settings(Request $request, Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('configure', $page);
|
||||
|
||||
$data = $request->validate([
|
||||
'slug' => ['required', 'string', 'max:120', 'regex:/^[a-z0-9]+(-[a-z0-9]+)*$/'],
|
||||
'in_navigation' => ['boolean'],
|
||||
], ['slug.regex' => 'Nur Kleinbuchstaben, Ziffern und Bindestriche.']);
|
||||
|
||||
$page->slug = $data['slug'];
|
||||
|
||||
// Hauptnavigation nur für Seiten der obersten Ebene – und nur mit „Seiten verwalten“.
|
||||
if ($page->parent_id === null && $request->user()->can('pages.manage')) {
|
||||
$page->in_navigation = (bool) ($data['in_navigation'] ?? false);
|
||||
}
|
||||
|
||||
$page->save();
|
||||
|
||||
return response()->json(['page' => $this->pageState($page, $request->user())]);
|
||||
}
|
||||
|
||||
public function destroy(Request $request, Page $page): RedirectResponse|JsonResponse
|
||||
{
|
||||
Gate::authorize('delete', $page);
|
||||
|
||||
if ($page->children()->exists()) {
|
||||
return response()->json(['message' => 'Die Seite hat Unterseiten. Bitte diese zuerst löschen oder verschieben.'], 422);
|
||||
}
|
||||
|
||||
$parent = $page->parent;
|
||||
$page->files->each->delete();
|
||||
$page->delete();
|
||||
|
||||
Audit::log('page.deleted', ['page' => $page->id, 'title' => $page->title]);
|
||||
|
||||
return response()->json(['redirect' => $parent?->url() ?? '/seiten']);
|
||||
}
|
||||
|
||||
public function revisions(Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
|
||||
return response()->json(['revisions' => $page->revisions()->with('user:id,name')->limit(50)->get(['id', 'page_id', 'title', 'action', 'user_id', 'created_at'])
|
||||
->map(fn (PageRevision $revision) => [
|
||||
'id' => $revision->id,
|
||||
'title' => $revision->title,
|
||||
'action' => PageRevision::ACTIONS[$revision->action] ?? $revision->action,
|
||||
'user' => $revision->user?->name,
|
||||
'created_at' => $revision->created_at?->toIso8601String(),
|
||||
])]);
|
||||
}
|
||||
|
||||
public function revision(Request $request, Page $page, PageRevision $revision): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
abort_unless($revision->page_id === $page->id, 404);
|
||||
|
||||
return response()->json([
|
||||
'title' => $revision->title,
|
||||
'content' => $this->content->render($revision->content, $request->user(), ['page_id' => $page->id]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function restore(Request $request, Page $page, PageRevision $revision): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
abort_unless($revision->page_id === $page->id, 404);
|
||||
|
||||
if ($response = $this->lockConflict($request, $page)) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
// Wiederherstellen legt einen Entwurf an – veröffentlicht wird wie immer ausdrücklich.
|
||||
$page->forceFill([
|
||||
'draft_title' => $revision->title,
|
||||
'draft' => $this->content->sanitize($revision->content),
|
||||
'draft_updated_at' => now(),
|
||||
'draft_updated_by' => $request->user()->id,
|
||||
])->save();
|
||||
|
||||
return response()->json(['page' => $this->pageState($page, $request->user()), 'working' => $page->workingCopy()]);
|
||||
}
|
||||
|
||||
public function lock(Request $request, Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
|
||||
if ($page->isLockedFor($request->user()) && ! $request->boolean('takeover')) {
|
||||
return response()->json(['lockedBy' => ['id' => $page->locked_by, 'name' => $page->lockedBy?->name]], 423);
|
||||
}
|
||||
|
||||
$page->lockFor($request->user());
|
||||
|
||||
return response()->json(['locked_until' => $page->locked_until->toIso8601String()]);
|
||||
}
|
||||
|
||||
public function unlock(Request $request, Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
$page->unlockFor($request->user());
|
||||
|
||||
return response()->json(['ok' => true]);
|
||||
}
|
||||
|
||||
public function uploadImage(Request $request, Page $page, Images $images): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
$request->validate(['image' => ['required', File::image()->types(['jpg', 'jpeg', 'png', 'webp', 'gif'])->max(15 * 1024)]]);
|
||||
|
||||
$path = $images->storeContentImage($request->file('image'), 'pagebuilder/pages/'.$page->id);
|
||||
|
||||
return response()->json(['path' => $path, 'url' => Blocks::imageUrl($path)]);
|
||||
}
|
||||
|
||||
public function uploadFile(Request $request, Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
$request->validate(['file' => ['required', 'file', 'max:'.(50 * 1024)]]);
|
||||
|
||||
$upload = $request->file('file');
|
||||
$name = Str::limit(preg_replace('/[^\pL\pN ._()\-]+/u', '_', $upload->getClientOriginalName()) ?: 'datei', 180, '');
|
||||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||||
|
||||
if (in_array($extension, self::BLOCKED_EXTENSIONS, true) || in_array(strtolower($upload->getClientOriginalExtension()), self::BLOCKED_EXTENSIONS, true)) {
|
||||
return response()->json(['message' => 'Dieser Dateityp ist aus Sicherheitsgründen nicht erlaubt.', 'errors' => ['file' => ['Dieser Dateityp ist nicht erlaubt.']]], 422);
|
||||
}
|
||||
|
||||
$path = $upload->storeAs('pages/'.$page->id, Str::random(32).($extension ? '.'.$extension : ''), PageFile::DISK);
|
||||
|
||||
$file = $page->files()->create([
|
||||
'name' => $name,
|
||||
'path' => $path,
|
||||
'mime' => $upload->getMimeType(),
|
||||
'size' => $upload->getSize(),
|
||||
'uploaded_by' => $request->user()->id,
|
||||
]);
|
||||
|
||||
return response()->json(['file' => $file->toBlockArray()]);
|
||||
}
|
||||
|
||||
public function preview(Request $request, Page $page): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
$request->validate(['blocks' => ['required', 'array', 'max:100'], 'blocks.*' => ['array']]);
|
||||
|
||||
$props = [];
|
||||
|
||||
foreach ($request->input('blocks') as $block) {
|
||||
if (is_string($block['id'] ?? null)) {
|
||||
$props[$block['id']] = $this->content->preview($block, $request->user(), ['page_id' => $page->id]);
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json(['props' => (object) $props]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1: array<string, mixed>}
|
||||
*/
|
||||
private function validatedWorkingCopy(Request $request): array
|
||||
{
|
||||
$request->validate([
|
||||
'title' => ['required', 'string', 'max:200'],
|
||||
'content' => ['present', 'array'],
|
||||
]);
|
||||
|
||||
return [trim($request->input('title')), $this->content->sanitize($request->input('content'))];
|
||||
}
|
||||
|
||||
private function lockConflict(Request $request, Page $page): ?JsonResponse
|
||||
{
|
||||
if ($page->isLockedFor($request->user())) {
|
||||
return response()->json([
|
||||
'message' => ($page->lockedBy?->name ?? 'Jemand anderes').' bearbeitet diese Seite gerade.',
|
||||
'lockedBy' => ['id' => $page->locked_by, 'name' => $page->lockedBy?->name],
|
||||
], 423);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function pageState(Page $page, User $user): array
|
||||
{
|
||||
return [
|
||||
'id' => $page->id,
|
||||
'title' => $page->title,
|
||||
'slug' => $page->slug,
|
||||
'url' => $page->url(),
|
||||
'parent_id' => $page->parent_id,
|
||||
'in_navigation' => $page->in_navigation,
|
||||
'is_published' => $page->isPublished(),
|
||||
'published_at' => $page->published_at?->toIso8601String(),
|
||||
'has_draft' => $page->hasDraft(),
|
||||
'draft_updated_at' => $page->draft_updated_at?->toIso8601String(),
|
||||
'scheduled_at' => $page->scheduled_at?->toIso8601String(),
|
||||
'can' => [
|
||||
'publish' => $user->can('publish', $page),
|
||||
'configure' => $user->can('configure', $page),
|
||||
'delete' => $user->can('delete', $page),
|
||||
'create_child' => $user->can('create', [Page::class, $page]),
|
||||
'navigation' => $page->parent_id === null && $user->can('pages.manage'),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Auswahl für „Sichtbar für“ an einzelnen Blöcken.
|
||||
*
|
||||
* @return array{role: list<array{value: string, label: string}>, department: list<string>, location: list<string>}
|
||||
*/
|
||||
private function audienceOptions(): array
|
||||
{
|
||||
return Cache::remember('pagebuilder.audience-options', 300, fn () => [
|
||||
'role' => Role::query()->orderBy('name')->get(['id', 'name'])->map(fn (Role $role) => ['value' => (string) $role->id, 'label' => $role->name])->all(),
|
||||
'department' => User::query()->active()->whereNotNull('department')->distinct()->orderBy('department')->pluck('department')->all(),
|
||||
'location' => User::query()->active()->whereNotNull('location')->distinct()->orderBy('location')->pluck('location')->all(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
239
plugins-core/pages/src/Models/Page.php
Normal file
239
plugins-core/pages/src/Models/Page.php
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages\Models;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Content;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Inhaus\Plugins\Pages\PageTree;
|
||||
|
||||
/**
|
||||
* Eine Inhaltsseite im Seitenbaum. Inhalt, Entwurf und geplanter Stand sind
|
||||
* bereinigtes Block-JSON (siehe App\Pagebuilder\Content).
|
||||
*/
|
||||
#[Fillable(['parent_id', 'title', 'slug', 'sort', 'in_navigation', 'created_by'])]
|
||||
class Page extends Model
|
||||
{
|
||||
/** So lange hält eine Bearbeitungssperre ohne Lebenszeichen des Editors. */
|
||||
public const LOCK_SECONDS = 120;
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saving(function (Page $page) {
|
||||
$page->slug = Str::slug($page->slug ?: $page->title, language: 'de') ?: 'seite';
|
||||
|
||||
if ($page->isDirty(['slug', 'parent_id']) || $page->path === null) {
|
||||
$page->path = static::uniquePath($page);
|
||||
}
|
||||
});
|
||||
|
||||
// Unterseiten ziehen mit, wenn sich die Adresse ändert.
|
||||
static::saved(function (Page $page) {
|
||||
if (! $page->wasRecentlyCreated && $page->wasChanged('path')) {
|
||||
$old = $page->getOriginal('path');
|
||||
|
||||
DB::table('pages')->where('path', 'like', str_replace(['%', '_'], ['\%', '\_'], $old).'/%')->update([
|
||||
'path' => DB::raw('CONCAT('.DB::getPdo()->quote($page->path).', SUBSTRING(path, '.(mb_strlen($old) + 1).'))'),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($page->wasRecentlyCreated || $page->wasChanged(['title', 'path', 'parent_id', 'sort', 'in_navigation', 'published_at'])) {
|
||||
PageTree::flush($page->wasRecentlyCreated || $page->wasChanged('parent_id'));
|
||||
}
|
||||
});
|
||||
|
||||
static::deleted(fn () => PageTree::flush(true));
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'content' => 'array',
|
||||
'draft' => 'array',
|
||||
'scheduled_content' => 'array',
|
||||
'in_navigation' => 'boolean',
|
||||
'published_at' => 'datetime',
|
||||
'draft_updated_at' => 'datetime',
|
||||
'scheduled_at' => 'datetime',
|
||||
'locked_until' => 'datetime',
|
||||
'locked_by' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1: int}
|
||||
*/
|
||||
public function permissionResource(): array
|
||||
{
|
||||
return ['page', $this->id];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Page, $this>
|
||||
*/
|
||||
public function parent(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Page::class, 'parent_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<Page, $this>
|
||||
*/
|
||||
public function children(): HasMany
|
||||
{
|
||||
return $this->hasMany(Page::class, 'parent_id')->orderBy('sort')->orderBy('title');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<PageRevision, $this>
|
||||
*/
|
||||
public function revisions(): HasMany
|
||||
{
|
||||
return $this->hasMany(PageRevision::class)->latest('id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<PageFile, $this>
|
||||
*/
|
||||
public function files(): HasMany
|
||||
{
|
||||
return $this->hasMany(PageFile::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function lockedBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'locked_by');
|
||||
}
|
||||
|
||||
public function isPublished(): bool
|
||||
{
|
||||
return $this->content !== null;
|
||||
}
|
||||
|
||||
public function hasDraft(): bool
|
||||
{
|
||||
return $this->draft !== null;
|
||||
}
|
||||
|
||||
public function url(): string
|
||||
{
|
||||
return '/seiten/'.$this->path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stand, mit dem der Editor startet: Entwurf, sonst veröffentlichter Inhalt.
|
||||
*
|
||||
* @return array{title: string, content: array<string, mixed>}
|
||||
*/
|
||||
public function workingCopy(): array
|
||||
{
|
||||
return [
|
||||
'title' => $this->draft_title ?? $this->title,
|
||||
'content' => $this->draft ?? $this->content ?? Content::empty(),
|
||||
];
|
||||
}
|
||||
|
||||
public function isLockedFor(User $user): bool
|
||||
{
|
||||
return $this->locked_by !== null && $this->locked_by !== $user->id && $this->locked_until?->isFuture();
|
||||
}
|
||||
|
||||
public function lockFor(User $user): void
|
||||
{
|
||||
$this->forceFill(['locked_by' => $user->id, 'locked_until' => now()->addSeconds(self::LOCK_SECONDS)])->saveQuietly();
|
||||
}
|
||||
|
||||
public function unlockFor(User $user): void
|
||||
{
|
||||
if ($this->locked_by === $user->id) {
|
||||
$this->forceFill(['locked_by' => null, 'locked_until' => null])->saveQuietly();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stand veröffentlichen und als Version ablegen.
|
||||
*
|
||||
* @param array<string, mixed> $content bereinigt
|
||||
*/
|
||||
public function publish(string $title, array $content, ?User $user, string $action = 'published'): void
|
||||
{
|
||||
DB::transaction(function () use ($title, $content, $user, $action) {
|
||||
$this->forceFill([
|
||||
'title' => $title,
|
||||
'content' => $content,
|
||||
'published_at' => now(),
|
||||
'published_by' => $user?->id,
|
||||
'draft' => null,
|
||||
'draft_title' => null,
|
||||
'draft_updated_at' => null,
|
||||
'draft_updated_by' => null,
|
||||
])->save();
|
||||
|
||||
$this->revisions()->create(['title' => $title, 'content' => $content, 'action' => $action, 'user_id' => $user?->id, 'created_at' => now()]);
|
||||
|
||||
// Nur die letzten 50 Versionen behalten.
|
||||
$keep = $this->revisions()->limit(50)->pluck('id');
|
||||
$this->revisions()->whereNotIn('id', $keep)->delete();
|
||||
});
|
||||
}
|
||||
|
||||
public function schedule(string $title, array $content, Carbon $at, User $user): void
|
||||
{
|
||||
$this->forceFill([
|
||||
'scheduled_at' => $at,
|
||||
'scheduled_title' => $title,
|
||||
'scheduled_content' => $content,
|
||||
'scheduled_by' => $user->id,
|
||||
'draft' => null,
|
||||
'draft_title' => null,
|
||||
'draft_updated_at' => null,
|
||||
'draft_updated_by' => null,
|
||||
])->save();
|
||||
}
|
||||
|
||||
public function cancelSchedule(): void
|
||||
{
|
||||
$this->forceFill(['scheduled_at' => null, 'scheduled_title' => null, 'scheduled_content' => null, 'scheduled_by' => null])->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fälligen geplanten Stand veröffentlichen (Hintergrundaufgabe und beim Aufruf).
|
||||
*/
|
||||
public function publishIfDue(): bool
|
||||
{
|
||||
if (! $this->scheduled_at || $this->scheduled_at->isFuture()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$by = $this->scheduled_by ? User::query()->find($this->scheduled_by) : null;
|
||||
$title = $this->scheduled_title ?? $this->title;
|
||||
$content = $this->scheduled_content ?? Content::empty();
|
||||
$this->cancelSchedule();
|
||||
$this->publish($title, $content, $by, 'scheduled');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function uniquePath(Page $page): string
|
||||
{
|
||||
$prefix = $page->parent_id ? static::query()->whereKey($page->parent_id)->value('path').'/' : '';
|
||||
$slug = $page->slug;
|
||||
|
||||
for ($i = 2; static::query()->where('path', $prefix.$slug)->when($page->exists, fn ($q) => $q->whereKeyNot($page->id))->exists(); $i++) {
|
||||
$slug = $page->slug.'-'.$i;
|
||||
}
|
||||
|
||||
$page->slug = $slug;
|
||||
|
||||
return $prefix.$slug;
|
||||
}
|
||||
}
|
||||
50
plugins-core/pages/src/Models/PageFile.php
Normal file
50
plugins-core/pages/src/Models/PageFile.php
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Datei zum Herunterladen (Block „Downloads“). Liegt außerhalb von public/ und
|
||||
* wird nur an Personen ausgeliefert, die die Seite sehen dürfen.
|
||||
*/
|
||||
#[Fillable(['page_id', 'name', 'path', 'mime', 'size', 'uploaded_by'])]
|
||||
class PageFile extends Model
|
||||
{
|
||||
public const DISK = 'local';
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::deleted(fn (PageFile $file) => Storage::disk(self::DISK)->delete($file->path));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Page, $this>
|
||||
*/
|
||||
public function page(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Page::class);
|
||||
}
|
||||
|
||||
public function url(): string
|
||||
{
|
||||
return route('pages.file', ['file' => $this->id, 'name' => $this->name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{id: int, name: string, size: int, extension: string, url: string}
|
||||
*/
|
||||
public function toBlockArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'size' => (int) $this->size,
|
||||
'extension' => strtoupper(pathinfo($this->name, PATHINFO_EXTENSION)),
|
||||
'url' => $this->url(),
|
||||
];
|
||||
}
|
||||
}
|
||||
41
plugins-core/pages/src/Models/PageRevision.php
Normal file
41
plugins-core/pages/src/Models/PageRevision.php
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages\Models;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable(['page_id', 'title', 'content', 'action', 'user_id', 'created_at'])]
|
||||
class PageRevision extends Model
|
||||
{
|
||||
public const UPDATED_AT = null;
|
||||
|
||||
public const ACTIONS = [
|
||||
'published' => 'Veröffentlicht',
|
||||
'scheduled' => 'Zeitgesteuert veröffentlicht',
|
||||
'restored' => 'Wiederhergestellt',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['content' => 'array'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Page, $this>
|
||||
*/
|
||||
public function page(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Page::class);
|
||||
}
|
||||
}
|
||||
204
plugins-core/pages/src/PageTree.php
Normal file
204
plugins-core/pages/src/PageTree.php
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\Permissions\Audiences;
|
||||
use App\Support\Permissions\Permissions;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Der Seitenbaum als gecachte Struktur (nur Arrays): Titel, Adressen,
|
||||
* Reihenfolge und Zielgruppen aller Seiten. Navigation, Seitenleiste,
|
||||
* Brotkrumen und Sichtbarkeit kommen ohne weitere Abfragen aus – auch bei
|
||||
* tausenden Seiten.
|
||||
*
|
||||
* Sichtbar ist eine Seite, wenn sie veröffentlicht ist und die Person die
|
||||
* Zielgruppe der Seite und aller übergeordneten Seiten erfüllt.
|
||||
*/
|
||||
class PageTree
|
||||
{
|
||||
private const CACHE_KEY = 'pages.tree';
|
||||
|
||||
/** @var array{pages: array<int, array<string, mixed>>, children: array<int, list<int>>}|null */
|
||||
private ?array $data = null;
|
||||
|
||||
/** @var array<int, array<int, bool>> */
|
||||
private array $visible = [];
|
||||
|
||||
public static function flush(bool $structureChanged = false): void
|
||||
{
|
||||
Cache::forget(self::CACHE_KEY);
|
||||
app(self::class)->data = null;
|
||||
app(self::class)->visible = [];
|
||||
|
||||
// Rechte „inkl. Unterseiten“ hängen am Baum.
|
||||
if ($structureChanged) {
|
||||
Permissions::flush();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public function get(int $id): ?array
|
||||
{
|
||||
return $this->data()['pages'][$id] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<int>
|
||||
*/
|
||||
public function childIds(?int $id): array
|
||||
{
|
||||
return $this->data()['children'][$id ?? 0] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $ids
|
||||
* @return list<int>
|
||||
*/
|
||||
public function descendantIds(array $ids): array
|
||||
{
|
||||
$result = [];
|
||||
$queue = $ids;
|
||||
|
||||
while ($queue !== []) {
|
||||
foreach ($this->childIds(array_shift($queue)) as $child) {
|
||||
if (! in_array($child, $result, true)) {
|
||||
$result[] = $child;
|
||||
$queue[] = $child;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Übergeordnete Seiten, beginnend bei der obersten.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function ancestors(int $id): array
|
||||
{
|
||||
$result = [];
|
||||
$parent = $this->get($id)['parent_id'] ?? null;
|
||||
|
||||
while ($parent !== null && ($page = $this->get($parent)) && count($result) < 50) {
|
||||
array_unshift($result, $page);
|
||||
$parent = $page['parent_id'];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function isVisible(int $id, ?User $user): bool
|
||||
{
|
||||
$key = $user?->id ?? 0;
|
||||
|
||||
if (isset($this->visible[$key][$id])) {
|
||||
return $this->visible[$key][$id];
|
||||
}
|
||||
|
||||
$page = $this->get($id);
|
||||
$visible = $page !== null
|
||||
&& $page['published']
|
||||
&& Audiences::matches($page['audience'], $user)
|
||||
&& ($page['parent_id'] === null || $this->isVisible($page['parent_id'], $user));
|
||||
|
||||
return $this->visible[$key][$id] = $visible;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sichtbare Unterseiten als verschachtelte Liste.
|
||||
*
|
||||
* @return list<array{id: int, title: string, url: string, children: list<mixed>}>
|
||||
*/
|
||||
public function visibleTree(?int $rootId, ?User $user, int $maxDepth = 6): array
|
||||
{
|
||||
if ($maxDepth <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$result = [];
|
||||
|
||||
foreach ($this->childIds($rootId) as $id) {
|
||||
if ($this->isVisible($id, $user)) {
|
||||
$page = $this->get($id);
|
||||
$result[] = [
|
||||
'id' => $id,
|
||||
'title' => $page['title'],
|
||||
'url' => '/seiten/'.$page['path'],
|
||||
'children' => $this->visibleTree($id, $user, $maxDepth - 1),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seiten der obersten Ebene, die in der Hauptnavigation stehen sollen.
|
||||
*
|
||||
* @return list<array{id: int, title: string, path: string, sort: int}>
|
||||
*/
|
||||
public function navigation(?User $user): array
|
||||
{
|
||||
return collect($this->childIds(null))
|
||||
->map(fn (int $id) => $this->get($id))
|
||||
->filter(fn (array $page) => $page['in_navigation'] && $this->isVisible($page['id'], $user))
|
||||
->map(fn (array $page) => ['id' => $page['id'], 'title' => $page['title'], 'path' => $page['path'], 'sort' => $page['sort']])
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Seiten mit Einrückung – für Auswahllisten.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function options(?int $rootId = null, int $depth = 0): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach ($this->childIds($rootId) as $id) {
|
||||
$options[$id] = str_repeat('— ', $depth).$this->get($id)['title'];
|
||||
$options += $this->options($id, $depth + 1);
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{pages: array<int, array<string, mixed>>, children: array<int, list<int>>}
|
||||
*/
|
||||
private function data(): array
|
||||
{
|
||||
return $this->data ??= Cache::rememberForever(self::CACHE_KEY, function () {
|
||||
$audiences = Audiences::allOfType('page');
|
||||
$pages = [];
|
||||
$children = [];
|
||||
|
||||
$rows = DB::table('pages')->orderBy('sort')->orderBy('title')
|
||||
->get(['id', 'parent_id', 'title', 'path', 'sort', 'in_navigation', 'published_at']);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$pages[$row->id] = [
|
||||
'id' => (int) $row->id,
|
||||
'parent_id' => $row->parent_id !== null ? (int) $row->parent_id : null,
|
||||
'title' => $row->title,
|
||||
'path' => $row->path,
|
||||
'sort' => (int) $row->sort,
|
||||
'in_navigation' => (bool) $row->in_navigation,
|
||||
'published' => $row->published_at !== null,
|
||||
'audience' => $audiences[$row->id] ?? null,
|
||||
];
|
||||
$children[(int) ($row->parent_id ?? 0)][] = (int) $row->id;
|
||||
}
|
||||
|
||||
return ['pages' => $pages, 'children' => $children];
|
||||
});
|
||||
}
|
||||
}
|
||||
102
plugins-core/pages/src/PagesPlugin.php
Normal file
102
plugins-core/pages/src/PagesPlugin.php
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages;
|
||||
|
||||
use App\Editorial\Editorial;
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Blocks;
|
||||
use App\Pagebuilder\BlockType;
|
||||
use App\Pagebuilder\Field;
|
||||
use App\Plugins\Plugin;
|
||||
use App\Support\Abilities;
|
||||
use App\Support\Navigation;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Schedule;
|
||||
use Inhaus\Plugins\Pages\Models\Page;
|
||||
use Inhaus\Plugins\Pages\Models\PageFile;
|
||||
use Inhaus\Plugins\Pages\Policies\PagePolicy;
|
||||
|
||||
class PagesPlugin extends Plugin
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->app->singleton(PageTree::class);
|
||||
|
||||
$abilities = $this->app->make(Abilities::class);
|
||||
$abilities->define('pages.manage', 'Seiten: alle Seiten verwalten', 'Seiten');
|
||||
$abilities->define('pages.edit', 'Seiten bearbeiten', 'Seiten', resource: 'page');
|
||||
$abilities->define('pages.publish', 'Seiten veröffentlichen', 'Seiten', resource: 'page');
|
||||
$abilities->resourceType(
|
||||
'page',
|
||||
'Seite',
|
||||
fn () => $this->app->make(PageTree::class)->options(),
|
||||
fn (array $ids) => $this->app->make(PageTree::class)->descendantIds($ids),
|
||||
);
|
||||
|
||||
Gate::policy(Page::class, PagePolicy::class);
|
||||
|
||||
// Seiten der obersten Ebene mit „In der Hauptnavigation“ erscheinen dort.
|
||||
$this->app->make(Navigation::class)->provider('pages', function (Request $request, ?User $user) {
|
||||
$current = trim((string) $request->route('path'), '/');
|
||||
|
||||
return array_map(fn (array $page) => [
|
||||
'key' => 'page-'.$page['id'],
|
||||
'label' => $page['title'],
|
||||
'href' => '/seiten/'.$page['path'],
|
||||
'active' => $request->routeIs('pages.show') && ($current === $page['path'] || str_starts_with($current, $page['path'].'/')),
|
||||
'sort' => 40 + $page['sort'],
|
||||
], $this->app->make(PageTree::class)->navigation($user));
|
||||
});
|
||||
|
||||
$this->app->make(Editorial::class)->add(
|
||||
'pages',
|
||||
'Seiten',
|
||||
'pages::EditorialPages',
|
||||
20,
|
||||
fn (User $user) => app(PagePolicy::class)->viewAny($user),
|
||||
fn (User $user) => EditorialPages::props($user),
|
||||
);
|
||||
|
||||
$this->registerBlocks($this->app->make(Blocks::class));
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
// Zeitgesteuerte Veröffentlichungen. Beim Aufruf einer Seite wird ein fälliger Stand zusätzlich sofort übernommen.
|
||||
Schedule::call(function () {
|
||||
Page::query()->whereNotNull('scheduled_at')->where('scheduled_at', '<=', now())->get()->each->publishIfDue();
|
||||
})->everyMinute()->name('pages-scheduled')->withoutOverlapping(5);
|
||||
}
|
||||
|
||||
private function registerBlocks(Blocks $blocks): void
|
||||
{
|
||||
$blocks->add(BlockType::make('downloads', 'Downloads', 'file-down', 'media', 'pages::Downloads')
|
||||
->description('Dateien zum Herunterladen – nur für Personen, die die Seite sehen dürfen.')
|
||||
->fields([
|
||||
Field::text('title', 'Überschrift', 150),
|
||||
Field::ids('files', 'Dateien', 'page-file'),
|
||||
])
|
||||
->resolveUsing(function (array $data, ?User $user, array $context) {
|
||||
$files = PageFile::query()->whereIn('id', $data['files'])
|
||||
->when(isset($context['page_id']), fn ($q) => $q->where('page_id', $context['page_id']))
|
||||
->get()->keyBy('id');
|
||||
|
||||
return ['files' => collect($data['files'])->map(fn ($id) => $files->get($id)?->toBlockArray())->filter()->values()->all()];
|
||||
}));
|
||||
|
||||
$blocks->add(BlockType::make('subpages', 'Unterseiten', 'folder-tree', 'dynamic', 'pages::Subpages')
|
||||
->description('Verweise auf die Unterseiten dieser Seite.')
|
||||
->fields([
|
||||
Field::text('title', 'Überschrift', 150),
|
||||
Field::select('layout', 'Darstellung', ['cards' => 'Kacheln', 'list' => 'Liste'], 'cards'),
|
||||
])
|
||||
->resolveUsing(function (array $data, ?User $user, array $context) {
|
||||
$tree = $this->app->make(PageTree::class);
|
||||
|
||||
return ['pages' => isset($context['page_id'])
|
||||
? array_map(fn (array $page) => ['id' => $page['id'], 'title' => $page['title'], 'url' => $page['url']], $tree->visibleTree($context['page_id'], $user, 1))
|
||||
: []];
|
||||
}));
|
||||
}
|
||||
}
|
||||
47
plugins-core/pages/src/Policies/PagePolicy.php
Normal file
47
plugins-core/pages/src/Policies/PagePolicy.php
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages\Policies;
|
||||
|
||||
use App\Models\User;
|
||||
use Inhaus\Plugins\Pages\Models\Page;
|
||||
|
||||
/**
|
||||
* Rechte an Seiten: „Seiten verwalten“ gilt für den ganzen Baum. „Bearbeiten“
|
||||
* und „Veröffentlichen“ werden je Seite vergeben, meist inkl. Unterseiten –
|
||||
* z. B. darf die MAV die Seite „MAV“ und alles darunter pflegen.
|
||||
*/
|
||||
class PagePolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return $user->can('pages.manage') || $user->permissions()->ids('pages.edit', 'page') !== [];
|
||||
}
|
||||
|
||||
public function create(User $user, ?Page $parent = null): bool
|
||||
{
|
||||
return $user->can('pages.manage') || ($parent !== null && $this->update($user, $parent));
|
||||
}
|
||||
|
||||
public function update(User $user, Page $page): bool
|
||||
{
|
||||
return $user->can('pages.manage') || $user->can('pages.edit', ['page', $page->id]);
|
||||
}
|
||||
|
||||
public function publish(User $user, Page $page): bool
|
||||
{
|
||||
return $user->can('pages.manage') || $user->can('pages.publish', ['page', $page->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adresse, Navigation und Sichtbarkeit: wer veröffentlichen darf.
|
||||
*/
|
||||
public function configure(User $user, Page $page): bool
|
||||
{
|
||||
return $this->publish($user, $page);
|
||||
}
|
||||
|
||||
public function delete(User $user, Page $page): bool
|
||||
{
|
||||
return $this->publish($user, $page) && ($page->parent_id !== null || $user->can('pages.manage'));
|
||||
}
|
||||
}
|
||||
38
plugins-core/pages/src/Publishers.php
Normal file
38
plugins-core/pages/src/Publishers.php
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Pages;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inhaus\Plugins\Pages\Models\Page;
|
||||
|
||||
/**
|
||||
* Wer eine Seite veröffentlichen darf – Empfänger von Freigabe-Anfragen.
|
||||
*/
|
||||
final class Publishers
|
||||
{
|
||||
/**
|
||||
* @return Collection<int, User>
|
||||
*/
|
||||
public static function for(Page $page, ?User $except = null): Collection
|
||||
{
|
||||
$ancestors = array_column(app(PageTree::class)->ancestors($page->id), 'id');
|
||||
|
||||
$roleIds = DB::table('grants')
|
||||
->where(function ($q) use ($page, $ancestors) {
|
||||
$q->whereIn('ability', ['*', 'pages.manage'])->whereNull('resource_type');
|
||||
$q->orWhere(fn ($q) => $q->where('ability', 'pages.publish')->where('resource_type', 'page')->where(fn ($q) => $q
|
||||
->whereNull('resource_id')
|
||||
->orWhere('resource_id', $page->id)
|
||||
->orWhere(fn ($q) => $q->whereIn('resource_id', $ancestors ?: [0])->where('include_children', true))));
|
||||
})
|
||||
->pluck('role_id');
|
||||
|
||||
return User::query()->active()
|
||||
->whereIn('id', DB::table('role_user')->whereIn('role_id', $roleIds)->select('user_id'))
|
||||
->when($except, fn ($q) => $q->whereKeyNot($except->id))
|
||||
->limit(50)
|
||||
->get();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue