Ideenbox-Moderation und Wochenüberblick per E-Mail (0.36.0)
Some checks failed
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 6m49s
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 7m19s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 7m29s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 7m39s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 9m38s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 9m25s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 7m57s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 8m4s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 46s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m9s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-27 15:17:47 +00:00
parent 11c5ef5baf
commit f9922f7308
172 changed files with 1524 additions and 363 deletions

View file

@ -0,0 +1,43 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Moderation: Meldungen zu Ideen und Kommentaren, vorläufiges Ausblenden.
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('ideas', function (Blueprint $table) {
$table->timestamp('hidden_at')->nullable()->after('comments_count');
});
Schema::table('idea_comments', function (Blueprint $table) {
$table->timestamp('hidden_at')->nullable()->after('official');
});
Schema::create('idea_reports', function (Blueprint $table) {
$table->id();
$table->foreignId('idea_id')->constrained('ideas')->cascadeOnDelete();
$table->foreignId('comment_id')->nullable()->constrained('idea_comments')->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('reason', 30);
$table->string('note', 500)->nullable();
$table->timestamp('resolved_at')->nullable();
$table->timestamps();
$table->unique(['user_id', 'idea_id', 'comment_id']);
$table->index(['resolved_at', 'idea_id']);
});
}
public function down(): void
{
Schema::dropIfExists('idea_reports');
Schema::table('idea_comments', fn (Blueprint $table) => $table->dropColumn('hidden_at'));
Schema::table('ideas', fn (Blueprint $table) => $table->dropColumn('hidden_at'));
}
};

View file

@ -0,0 +1,37 @@
<script setup>
import { router } from '@inertiajs/vue3';
import { Flag } from '@lucide/vue';
import { Button } from '@/components/ui/button';
/**
* Für das Gremium: offene Meldungen zu einer Idee oder einem Kommentar – behalten oder löschen.
*/
const props = defineProps({
ideaId: { type: Number, required: true },
commentId: { type: Number, default: null },
reports: { type: Array, required: true },
hidden: { type: Boolean, default: false },
});
function decide(action) {
if (action === 'remove' && !window.confirm(props.commentId ? 'Kommentar löschen?' : 'Idee samt Kommentaren löschen?')) return;
router.put(`/ideen/${props.ideaId}/meldungen`, { comment_id: props.commentId, action }, { preserveScroll: true });
}
</script>
<template>
<div class="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm" role="status">
<p class="flex items-center gap-2 font-medium">
<Flag class="size-4 text-destructive" />
{{ reports.length }} {{ reports.length === 1 ? 'Meldung' : 'Meldungen' }}<template v-if="hidden"> · vorläufig ausgeblendet</template>
</p>
<ul class="mt-1.5 grid gap-0.5 pl-6 text-[13px] text-muted-foreground">
<li v-for="(report, i) in reports" :key="i">{{ report.reason }}<template v-if="report.note">: „{{ report.note }}“</template></li>
</ul>
<div class="mt-3 flex flex-wrap gap-2 pl-6">
<Button size="sm" variant="outline" @click="decide('keep')">In Ordnung – behalten</Button>
<Button size="sm" variant="outline" class="text-destructive hover:text-destructive" @click="decide('remove')">Löschen</Button>
</div>
</div>
</template>

View file

@ -0,0 +1,63 @@
<script setup>
import { watch } from 'vue';
import { useForm } from '@inertiajs/vue3';
import { LoaderCircle } from '@lucide/vue';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
/**
* Idee oder Kommentar melden. Das Gremium sieht Grund und Anmerkung, nicht den Namen.
*/
const props = defineProps({
ideaId: { type: Number, required: true },
commentId: { type: Number, default: null },
reasons: { type: Object, required: true },
});
const open = defineModel('open', { type: Boolean, default: false });
const form = useForm({ reason: '', note: '', comment_id: null });
watch(open, (value) => {
if (!value) return;
form.reset();
form.clearErrors();
form.comment_id = props.commentId;
});
function submit() {
form.post(`/ideen/${props.ideaId}/melden`, { preserveScroll: true, onSuccess: () => (open.value = false) });
}
</script>
<template>
<Dialog v-model:open="open">
<DialogContent class="sm:max-w-md">
<DialogHeader>
<DialogTitle>{{ commentId ? 'Kommentar melden' : 'Idee melden' }}</DialogTitle>
<DialogDescription>Das Gremium prüft den Hinweis. Ihr Name wird dabei nicht angezeigt.</DialogDescription>
</DialogHeader>
<form id="report-form" class="grid gap-4" @submit.prevent="submit">
<fieldset class="grid gap-2">
<legend class="mb-2 text-sm font-medium">Warum?</legend>
<label v-for="(label, key) in reasons" :key="key" class="flex cursor-pointer items-center gap-3 rounded-md border px-3 py-2 text-sm hover:bg-accent/50 has-[:checked]:border-brand has-[:checked]:bg-brand-soft">
<input v-model="form.reason" type="radio" name="reason" :value="key" class="size-4 accent-[var(--color-brand)]" />
{{ label }}
</label>
</fieldset>
<div class="grid gap-1.5">
<label for="report-note" class="text-sm font-medium">Anmerkung (optional)</label>
<Textarea id="report-note" v-model="form.note" rows="2" maxlength="500" />
</div>
<p v-if="form.errors.reason" class="text-[13px] text-destructive">Bitte einen Grund auswählen.</p>
</form>
<DialogFooter>
<Button variant="ghost" @click="open = false">Abbrechen</Button>
<Button type="submit" form="report-form" :disabled="form.processing || !form.reason">
<LoaderCircle v-if="form.processing" class="animate-spin" /> Melden
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</template>

View file

@ -1,17 +1,28 @@
<script setup>
import { Link } from '@inertiajs/vue3';
import { MessageCircle, ThumbsUp } from '@lucide/vue';
import { EyeOff, Flag, MessageCircle, ThumbsUp } from '@lucide/vue';
import Panel from '@/components/Panel.vue';
import { formatRelative } from '@/lib/format';
import StatusBadge from '../components/StatusBadge.vue';
defineProps({
ideas: { type: Array, required: true },
reported: { type: Array, default: () => [] },
});
</script>
<template>
<Panel title="Ideenbox – zu sichten" action-label="Alle Ideen" action-href="/ideen">
<template v-if="reported.length">
<h3 class="mb-2 flex items-center gap-1.5 text-xs font-semibold tracking-wider text-destructive uppercase"><Flag class="size-3.5" /> Gemeldet</h3>
<ul class="-mx-5 mb-5 divide-y border-y">
<li v-for="idea in reported" :key="idea.id" class="flex items-center gap-3 px-5 py-2.5">
<Link :href="idea.url" class="min-w-0 flex-1 truncate text-sm font-medium hover:underline">{{ idea.title }}</Link>
<EyeOff v-if="idea.hidden" class="size-3.5 shrink-0 text-muted-foreground" title="Vorläufig ausgeblendet" />
<span class="shrink-0 text-xs text-destructive tabular-nums">{{ idea.reports }} {{ idea.reports === 1 ? 'Meldung' : 'Meldungen' }}</span>
</li>
</ul>
</template>
<ul v-if="ideas.length" class="-mx-5 divide-y border-t">
<li v-for="idea in ideas" :key="idea.id" class="flex items-center gap-3 px-5 py-2.5">
<div class="min-w-0 flex-1">

View file

@ -1,7 +1,7 @@
<script setup>
import { ref, watch } from 'vue';
import { Link, router, useForm, usePage } from '@inertiajs/vue3';
import { BadgeCheck, LoaderCircle, PencilLine, Trash2 } from '@lucide/vue';
import { BadgeCheck, EyeOff, Flag, LoaderCircle, PencilLine, Trash2 } from '@lucide/vue';
import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
@ -13,14 +13,25 @@ import PersonAvatar from '@/components/PersonAvatar.vue';
import AppLayout from '@/layouts/AppLayout.vue';
import { formatDate, formatRelative } from '@/lib/format';
import IdeaDialog from '../components/IdeaDialog.vue';
import ModerationNotice from '../components/ModerationNotice.vue';
import ReportDialog from '../components/ReportDialog.vue';
import StatusBadge from '../components/StatusBadge.vue';
import SupportButton from '../components/SupportButton.vue';
const props = defineProps({
idea: { type: Object, required: true },
statuses: { type: Object, required: true },
reasons: { type: Object, required: true },
});
// Melden
const reporting = ref(false);
const reportComment = ref(null);
function report(commentId = null) {
reportComment.value = commentId;
reporting.value = true;
}
const page = usePage();
watch(() => page.props.flash.status, (status) => status && toast.success(status), { immediate: true });
@ -55,14 +66,19 @@ function remove() {
eingereicht {{ formatRelative(idea.created_at) }}<template v-if="!idea.author"> · anonym</template>
</span>
</template>
<template v-if="idea.can_edit || idea.can_manage" #actions>
<template #actions>
<Button v-if="idea.can_edit" variant="outline" size="sm" @click="editing = true"><PencilLine /> Bearbeiten</Button>
<Button variant="ghost" size="sm" class="text-destructive hover:text-destructive" @click="remove"><Trash2 /> Löschen</Button>
<Button v-if="idea.can_edit || idea.can_manage" variant="ghost" size="sm" class="text-destructive hover:text-destructive" @click="remove"><Trash2 /> Löschen</Button>
<Button v-if="!idea.mine && !idea.can_manage" variant="ghost" size="sm" class="text-muted-foreground" :disabled="idea.reported" @click="report()">
<Flag /> {{ idea.reported ? 'Gemeldet' : 'Melden' }}
</Button>
</template>
</PageHeader>
<div class="grid items-start gap-6 lg:grid-cols-12">
<div class="grid min-w-0 gap-6 lg:col-span-8">
<ModerationNotice v-if="idea.can_manage && idea.reports.length" :idea-id="idea.id" :reports="idea.reports" :hidden="idea.hidden" />
<p v-else-if="idea.hidden" class="flex items-center gap-2 rounded-md border bg-muted/60 p-3 text-sm"><EyeOff class="size-4 shrink-0" /> Ihre Idee ist vorläufig ausgeblendet, weil sie gemeldet wurde. Das Gremium prüft sie.</p>
<Panel>
<div class="flex gap-5">
<SupportButton :idea="idea" :disabled="idea.mine" large />
@ -85,7 +101,7 @@ function remove() {
<Panel id="kommentare" :title="`Kommentare (${idea.comment_list.length})`">
<ul v-if="idea.comment_list.length" class="-mx-5 mb-5 divide-y border-y">
<li v-for="c in idea.comment_list" :key="c.id" class="flex gap-3 px-5 py-4" :class="{ 'bg-brand-soft/40': c.official }">
<li v-for="c in idea.comment_list" :id="`kommentar-${c.id}`" :key="c.id" class="flex gap-3 px-5 py-4" :class="{ 'bg-brand-soft/40': c.official }">
<PersonAvatar v-if="c.author" :person="c.author" class="size-9" />
<div class="min-w-0 flex-1">
<p class="flex flex-wrap items-center gap-x-2 text-sm">
@ -93,8 +109,20 @@ function remove() {
<span v-if="c.official" class="inline-flex items-center gap-1 text-xs font-medium text-brand-text"><BadgeCheck class="size-3.5" /> Gremium</span>
<span class="text-xs text-muted-foreground">{{ formatRelative(c.created_at) }}</span>
</p>
<p class="mt-1 text-sm leading-relaxed whitespace-pre-line">{{ c.body }}</p>
<p v-if="c.body === null" class="mt-1 flex items-center gap-1.5 text-sm text-muted-foreground italic"><EyeOff class="size-3.5" /> Vorläufig ausgeblendet – wird geprüft.</p>
<p v-else class="mt-1 text-sm leading-relaxed whitespace-pre-line" :class="{ 'opacity-60': c.hidden }">{{ c.body }}</p>
<ModerationNotice v-if="idea.can_manage && c.reports.length" :idea-id="idea.id" :comment-id="c.id" :reports="c.reports" :hidden="c.hidden" class="mt-2" />
</div>
<Button
v-if="!c.can_delete && c.body !== null"
variant="ghost"
size="icon"
class="size-7 shrink-0 text-muted-foreground"
:disabled="c.reported"
:aria-label="c.reported ? 'Bereits gemeldet' : 'Kommentar melden'"
:title="c.reported ? 'Bereits gemeldet' : 'Kommentar melden'"
@click="report(c.id)"
><Flag class="size-3.5" /></Button>
<Button v-if="c.can_delete" variant="ghost" size="icon" class="size-7 shrink-0 text-muted-foreground hover:text-destructive" aria-label="Kommentar löschen" @click="deleteComment(c)"><Trash2 class="size-3.5" /></Button>
</li>
</ul>
@ -138,5 +166,6 @@ function remove() {
</div>
<IdeaDialog v-if="idea.can_edit" v-model:open="editing" :idea="idea" />
<ReportDialog v-model:open="reporting" :idea-id="idea.id" :comment-id="reportComment" :reasons="reasons" />
</AppLayout>
</template>

View file

@ -10,5 +10,6 @@ Route::controller(IdeaController::class)->group(function () {
Route::get('/ideas/{idea}', 'show')->whereNumber('idea');
Route::post('/ideas/{idea}/support', 'support')->whereNumber('idea')->middleware('throttle:60,1');
Route::delete('/ideas/{idea}/support', 'unsupport')->whereNumber('idea')->middleware('throttle:60,1');
Route::post('/ideas/{idea}/report', 'report')->whereNumber('idea')->middleware('throttle:20,60');
Route::post('/ideas/{idea}/comments', 'comment')->whereNumber('idea')->middleware('throttle:20,1');
});

View file

@ -14,4 +14,6 @@ Route::middleware('auth')->prefix('ideen')->name('ideas.')->controller(IdeaContr
Route::post('/{idea}/kommentare', 'comment')->middleware('throttle:20,1')->name('comments.store');
Route::delete('/{idea}/kommentare/{comment}', 'deleteComment')->name('comments.destroy');
Route::put('/{idea}/status', 'status')->name('status');
Route::post('/{idea}/melden', 'report')->middleware('throttle:20,60')->name('report');
Route::put('/{idea}/meldungen', 'moderate')->name('moderate');
});

View file

@ -16,6 +16,8 @@ use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Ideen\Models\Idea;
use Inhaus\Plugins\Ideen\Models\IdeaComment;
use Inhaus\Plugins\Ideen\Models\IdeaReport;
use Inhaus\Plugins\Ideen\Moderation;
use Inhaus\Plugins\Ideen\Presenter;
/**
@ -33,6 +35,7 @@ class IdeaController extends Controller
$user = $request->user();
$ideas = Idea::query()->with('author')
->when(! $user->can('ideas.manage'), fn ($q) => $q->where(fn ($q) => $q->whereNull('hidden_at')->orWhere(fn ($q) => $q->where('author_id', $user->id)->where('anonymous', false))))
->when($data['status'] ?? null, fn ($q, $status) => $q->where('status', $status))
->when($data['q'] ?? null, fn ($q, $term) => $q->where(fn ($q) => $q->where('title', 'like', '%'.addcslashes($term, '%_\\').'%')->orWhere('body', 'like', '%'.addcslashes($term, '%_\\').'%')))
->when(($data['sortierung'] ?? 'neu') === 'beliebt', fn ($q) => $q->orderByDesc('supports_count'))
@ -58,11 +61,12 @@ class IdeaController extends Controller
public function show(Request $request, Idea $idea): Response|JsonResponse
{
$this->ensureVisible($request, $idea);
$detail = Presenter::detail($idea->load('author'), $request->user());
return $this->wantsJson($request)
? response()->json(['data' => $detail])
: Inertia::render('ideen::Show', ['idea' => $detail, 'statuses' => Idea::STATUSES]);
: Inertia::render('ideen::Show', ['idea' => $detail, 'statuses' => Idea::STATUSES, 'reasons' => IdeaReport::REASONS]);
}
public function store(Request $request): RedirectResponse|JsonResponse
@ -109,6 +113,7 @@ class IdeaController extends Controller
public function support(Request $request, Idea $idea): RedirectResponse|JsonResponse
{
$this->ensureVisible($request, $idea);
abort_if(! $idea->anonymous && $idea->author_id === $request->user()->id, 422, 'Die eigene Idee lässt sich nicht unterstützen.');
$idea->supporters()->syncWithoutDetaching([$request->user()->id => ['created_at' => now()]]);
@ -124,6 +129,7 @@ class IdeaController extends Controller
public function comment(Request $request, Idea $idea): RedirectResponse|JsonResponse
{
$this->ensureVisible($request, $idea);
$data = $request->validate(['body' => ['required', 'string', 'max:'.IdeaComment::MAX_LENGTH], 'official' => ['boolean']], [], ['body' => 'Kommentar']);
$user = $request->user();
$official = ($data['official'] ?? false) && $user->can('ideas.manage');
@ -192,6 +198,51 @@ class IdeaController extends Controller
return back()->with('status', 'Status gespeichert.');
}
/** Etwas melden – die Idee selbst oder einen Kommentar */
public function report(Request $request, Idea $idea, Moderation $moderation): RedirectResponse|JsonResponse
{
$this->ensureVisible($request, $idea);
$data = $request->validate([
'reason' => ['required', Rule::in(array_keys(IdeaReport::REASONS))],
'note' => ['nullable', 'string', 'max:500'],
'comment_id' => ['nullable', 'integer'],
]);
$comment = isset($data['comment_id']) ? $idea->comments()->findOrFail($data['comment_id']) : null;
$own = $comment ? $comment->user_id === $request->user()->id : (! $idea->anonymous && $idea->author_id === $request->user()->id);
abort_if($own, 422, 'Eigene Beiträge lassen sich nicht melden.');
$moderation->report($idea, $comment, $request->user(), $data['reason'], filled($data['note'] ?? null) ? trim($data['note']) : null);
return $this->wantsJson($request)
? response()->json(['message' => 'Danke, das Gremium sieht es sich an.'])
: back()->with('status', 'Danke für den Hinweis – das Gremium sieht es sich an.');
}
/** Gremium: Meldungen erledigen */
public function moderate(Request $request, Idea $idea, Moderation $moderation): RedirectResponse
{
Gate::authorize('ideas.manage');
$data = $request->validate(['comment_id' => ['nullable', 'integer'], 'action' => ['required', 'in:keep,remove']]);
$comment = isset($data['comment_id']) ? $idea->comments()->findOrFail($data['comment_id']) : null;
$moderation->resolve($idea, $comment, $data['action'] === 'remove');
Audit::log('idea.moderated', ['idea' => $idea->id, 'comment' => $comment?->id, 'action' => $data['action']]);
if ($data['action'] === 'remove' && ! $comment) {
return to_route('ideas.index')->with('status', 'Idee gelöscht.');
}
return back()->with('status', $data['action'] === 'remove' ? 'Kommentar gelöscht.' : 'Meldungen erledigt – der Inhalt ist wieder sichtbar.');
}
/** Ausgeblendete Ideen sehen nur das Gremium und die einreichende Person */
private function ensureVisible(Request $request, Idea $idea): void
{
$user = $request->user();
abort_if($idea->hidden_at && ! $user->can('ideas.manage') && ($idea->anonymous || $idea->author_id !== $user->id), 404);
}
/**
* @return array{title: string, body: string}
*/

View file

@ -3,11 +3,13 @@
namespace Inhaus\Plugins\Ideen;
use App\Dashboard\Widgets;
use App\Digest\Digest;
use App\Editorial\Editorial;
use App\Models\User;
use App\Plugins\Plugin;
use App\Support\Abilities;
use App\Support\Navigation;
use Carbon\CarbonImmutable;
use Inhaus\Plugins\Ideen\Models\Idea;
class IdeenPlugin extends Plugin
@ -15,12 +17,22 @@ class IdeenPlugin extends Plugin
public function register(): void
{
$this->app->make(Navigation::class)->add('ideen', 'Ideenbox', '/ideen', active: 'ideas.*', sort: 76);
$this->app->make(Digest::class)->add('ideen', 'Neue Ideen', 40, fn (User $user, CarbonImmutable $since) => Idea::query()
->whereNull('hidden_at')->where('created_at', '>=', $since)->orderByDesc('supports_count')->latest()->limit(5)->get()
->map(fn (Idea $idea) => [
'title' => $idea->title,
'url' => route('ideas.show', $idea),
'meta' => $idea->supports_count.' '.($idea->supports_count === 1 ? 'Unterstützung' : 'Unterstützungen'),
])->all());
$this->app->make(Abilities::class)->define('ideas.manage', 'Ideen bewerten, beantworten und moderieren (Gremium)', 'Ideenbox', portal: true);
// Redaktion: was das Gremium noch sichten muss
$this->app->make(Editorial::class)->add('ideen', 'Ideenbox', 'ideen::EditorialIdeas', 34,
fn (User $user) => $user->can('ideas.manage'),
fn (User $user) => [
'reported' => Idea::query()->with('author')->whereHas('reports', fn ($q) => $q->whereNull('resolved_at'))->withCount(['reports' => fn ($q) => $q->whereNull('resolved_at')])
->latest()->limit(20)->get()->map(fn (Idea $idea) => [...Presenter::card($idea), 'reports' => $idea->reports_count, 'hidden' => $idea->hidden_at !== null])->all(),
'ideas' => Idea::query()->with('author')->whereIn('status', ['new', 'review'])
->orderByRaw("status = 'new' DESC")->orderByDesc('supports_count')->latest()->limit(30)->get()
->map(fn (Idea $idea) => Presenter::card($idea))->all(),
@ -28,7 +40,7 @@ class IdeenPlugin extends Plugin
// Startseite: beliebteste offene Ideen
$this->app->make(Widgets::class)->add('ideen.popular', 'ideen::Popular', 'aside', sort: 28, props: function () {
$ideas = Idea::query()->with('author')->whereIn('status', ['new', 'review'])->where('created_at', '>=', now()->subDays(60))
$ideas = Idea::query()->with('author')->whereNull('hidden_at')->whereIn('status', ['new', 'review'])->where('created_at', '>=', now()->subDays(60))
->orderByDesc('supports_count')->latest()->limit(3)->get();
return $ideas->isEmpty() ? null : ['ideas' => $ideas->map(fn (Idea $idea) => Presenter::card($idea))->all()];

View file

@ -21,7 +21,7 @@ class Idea extends Model
protected function casts(): array
{
return ['anonymous' => 'boolean', 'status_changed_at' => 'datetime'];
return ['anonymous' => 'boolean', 'status_changed_at' => 'datetime', 'hidden_at' => 'datetime'];
}
/**
@ -48,6 +48,14 @@ class Idea extends Model
return $this->hasMany(IdeaComment::class);
}
/**
* @return HasMany<IdeaReport, $this>
*/
public function reports(): HasMany
{
return $this->hasMany(IdeaReport::class);
}
public function statusLabel(): string
{
return self::STATUSES[$this->status] ?? $this->status;

View file

@ -14,7 +14,7 @@ class IdeaComment extends Model
protected function casts(): array
{
return ['official' => 'boolean'];
return ['official' => 'boolean', 'hidden_at' => 'datetime'];
}
/**

View file

@ -0,0 +1,49 @@
<?php
namespace Inhaus\Plugins\Ideen\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['idea_id', 'comment_id', 'user_id', 'reason', 'note', 'resolved_at'])]
class IdeaReport extends Model
{
public const REASONS = [
'offensive' => 'Beleidigend oder respektlos',
'personal' => 'Nennt oder bloßstellt Personen',
'confidential' => 'Vertrauliche Informationen',
'spam' => 'Spam oder unpassend',
'other' => 'Sonstiges',
];
protected function casts(): array
{
return ['resolved_at' => 'datetime'];
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* @return BelongsTo<IdeaComment, $this>
*/
public function comment(): BelongsTo
{
return $this->belongsTo(IdeaComment::class);
}
/**
* @return BelongsTo<Idea, $this>
*/
public function idea(): BelongsTo
{
return $this->belongsTo(Idea::class);
}
}

View file

@ -0,0 +1,87 @@
<?php
namespace Inhaus\Plugins\Ideen;
use App\Models\User;
use App\Notifications\PortalNotification;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Inhaus\Plugins\Ideen\Models\Idea;
use Inhaus\Plugins\Ideen\Models\IdeaComment;
use Inhaus\Plugins\Ideen\Models\IdeaReport;
/**
* Meldungen in der Ideenbox: Wer etwas Unpassendes sieht, meldet es. Ab drei Meldungen
* verschiedener Personen wird der Inhalt vorläufig ausgeblendet, bis das Gremium entscheidet.
*/
class Moderation
{
public const HIDE_AFTER = 3;
public function report(Idea $idea, ?IdeaComment $comment, User $user, string $reason, ?string $note): void
{
$report = IdeaReport::query()->firstOrCreate(
['user_id' => $user->id, 'idea_id' => $idea->id, 'comment_id' => $comment?->id],
['reason' => $reason, 'note' => $note],
);
if (! $report->wasRecentlyCreated) {
return;
}
$open = IdeaReport::query()->where('idea_id', $idea->id)->where('comment_id', $comment?->id)->whereNull('resolved_at')->count();
$subject = $comment ?? $idea;
if ($open >= self::HIDE_AFTER && $subject->hidden_at === null) {
$subject->forceFill(['hidden_at' => now()])->save();
}
// Das Gremium bei der ersten offenen Meldung informieren (nicht bei jeder weiteren)
if ($open === 1) {
Notification::send($this->moderators()->reject(fn (User $u) => $u->id === $user->id), new PortalNotification(
($comment ? 'Kommentar gemeldet: ' : 'Idee gemeldet: ').Str::limit($idea->title, 60),
IdeaReport::REASONS[$reason] ?? $reason,
route('ideas.show', $idea, false).($comment ? '#kommentar-'.$comment->id : ''),
'flag',
));
}
}
/**
* Gremium: Meldungen erledigen – Inhalt bleibt (wieder sichtbar) oder wird gelöscht.
*/
public function resolve(Idea $idea, ?IdeaComment $comment, bool $remove): void
{
IdeaReport::query()->where('idea_id', $idea->id)->where('comment_id', $comment?->id)->whereNull('resolved_at')->update(['resolved_at' => now()]);
if ($remove) {
$comment ? $comment->delete() : $idea->delete();
$comment && $idea->refreshCounts();
return;
}
($comment ?? $idea)->forceFill(['hidden_at' => null])->save();
}
public function openCount(): int
{
return IdeaReport::query()->whereNull('resolved_at')->distinct()->count('idea_id');
}
/**
* Wer das Recht „ideas.manage“ über eine Rolle hat – ohne solche Personen die Administration.
*
* @return Collection<int, User>
*/
public function moderators(): Collection
{
$holders = fn (string $ability) => User::query()->active()
->whereHas('roles.grants', fn ($q) => $q->where('ability', $ability))->limit(50)->get();
$moderators = $holders('ideas.manage');
return $moderators->isNotEmpty() ? $moderators : $holders('*');
}
}

View file

@ -6,6 +6,7 @@ use App\Models\User;
use Illuminate\Support\Str;
use Inhaus\Plugins\Ideen\Models\Idea;
use Inhaus\Plugins\Ideen\Models\IdeaComment;
use Inhaus\Plugins\Ideen\Models\IdeaReport;
class Presenter
{
@ -35,6 +36,11 @@ class Presenter
public static function detail(Idea $idea, User $user): array
{
$manager = $user->can('ideas.manage');
$reports = IdeaReport::query()->where('idea_id', $idea->id)->get();
$mineReported = $reports->where('user_id', $user->id)->map(fn ($r) => $r->comment_id ?? 0)->all();
// Für das Gremium: offene Meldungen je Inhalt – Gründe und Anmerkungen, ohne Namen der Meldenden
$open = fn (?int $commentId) => $manager ? $reports->whereNull('resolved_at')->where('comment_id', $commentId)->values()
->map(fn (IdeaReport $r) => ['reason' => IdeaReport::REASONS[$r->reason] ?? $r->reason, 'note' => $r->note])->all() : [];
return [
...self::card($idea, $idea->supporters()->whereKey($user->id)->exists()),
@ -45,10 +51,17 @@ class Presenter
'mine' => ! $idea->anonymous && $idea->author_id === $user->id,
'can_edit' => ! $idea->anonymous && $idea->author_id === $user->id && $idea->status === 'new',
'can_manage' => $manager,
'hidden' => $idea->hidden_at !== null,
'reported' => in_array(0, $mineReported, true),
'reports' => $open(null),
'comment_list' => $idea->comments()->with('user')->oldest()->oldest('id')->limit(500)->get()
->map(fn (IdeaComment $c) => [
'id' => $c->id,
'body' => $c->body,
// Ausgeblendet: nur Gremium und die schreibende Person sehen den Text
'body' => $c->hidden_at && ! $manager && $c->user_id !== $user->id ? null : $c->body,
'hidden' => $c->hidden_at !== null,
'reported' => in_array($c->id, $mineReported, true),
'reports' => $open($c->id),
'official' => $c->official,
'created_at' => $c->created_at?->toIso8601String(),
'author' => $c->user ? ['id' => $c->user->id, 'name' => $c->user->name, 'initials' => $c->user->initials, 'avatar_url' => $c->user->avatarUrl(64)] : null,