Umfragen-Plugin (0.32.0)
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 5m33s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 5m25s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 6m7s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 5m54s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 9m9s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 10m55s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 10m12s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 1m26s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 9m48s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m52s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-27 12:54:17 +00:00
parent 08953d52cb
commit 3f67fde50b
153 changed files with 2075 additions and 329 deletions

View file

@ -0,0 +1,38 @@
<?php
namespace Inhaus\Plugins\Umfragen;
use App\Models\User;
use App\Notifications\PortalNotification;
use App\Plugins\PluginAccess;
use App\Support\Permissions\Audiences;
use Illuminate\Support\Facades\Notification;
use Inhaus\Plugins\Umfragen\Models\Poll;
/**
* Auf Wunsch der Redaktion: neue Umfrage einmal ankündigen – an ihre Zielgruppe.
*/
class Announcer
{
public function announceIfDue(Poll $poll): void
{
if (! $poll->announce || $poll->announced_at !== null || ! $poll->isOpen()) {
return;
}
$poll->forceFill(['announced_at' => now()])->save();
$rules = Audiences::get('poll', $poll->id);
$excluded = app(PluginAccess::class)->excludedRoles('umfragen');
$notification = new PortalNotification('Neue Umfrage: '.$poll->title, 'Ihre Meinung ist gefragt.', route('polls.show', $poll, false), 'vote');
User::query()->active()->whereKeyNot($poll->author_id ?? 0)
->when($excluded !== [], fn ($q) => $q->whereDoesntHave('roles', fn ($r) => $r->whereIn('roles.id', $excluded)))
->with('roles')
->chunkById(500, fn ($users) => Notification::send($users->filter(fn (User $u) => Audiences::matches($rules ?: null, $u)), $notification));
}
public function announceDue(): void
{
Poll::query()->open()->where('announce', true)->whereNull('announced_at')->get()->each(fn (Poll $poll) => $this->announceIfDue($poll));
}
}

View file

@ -0,0 +1,96 @@
<?php
namespace Inhaus\Plugins\Umfragen\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Umfragen\Models\Poll;
use Inhaus\Plugins\Umfragen\Models\PollResponse;
use Inhaus\Plugins\Umfragen\Presenter;
use Inhaus\Plugins\Umfragen\Questions;
class PollController extends Controller
{
public function index(Request $request): Response
{
return Inertia::render('umfragen::Index', [
...$this->lists($request),
'canManage' => $request->user()->can('polls.manage'),
]);
}
public function show(Request $request, Poll $poll): Response
{
$this->ensureVisible($request, $poll);
return Inertia::render('umfragen::Show', ['poll' => Presenter::present($poll, $request->user())]);
}
public function vote(Request $request, Poll $poll): RedirectResponse|JsonResponse
{
$this->ensureVisible($request, $poll);
$user = $request->user();
if (! $poll->isOpen()) {
throw ValidationException::withMessages(['answers' => 'Diese Umfrage ist beendet.']);
}
$answers = Questions::validate($poll->questions, $request->input('answers'));
try {
PollResponse::query()->create([
'poll_id' => $poll->id,
'user_id' => $poll->anonymous ? null : $user->id,
'voter' => $poll->voterKey($user),
'answers' => $answers,
'submitted_on' => today(),
]);
} catch (QueryException) {
throw ValidationException::withMessages(['answers' => 'Sie haben bereits teilgenommen.']);
}
if ($request->expectsJson() && ! $request->header('X-Inertia')) {
return response()->json(['message' => 'Danke für Ihre Teilnahme!', 'data' => Presenter::present($poll, $user)]);
}
return back()->with('status', 'Danke für Ihre Teilnahme!');
}
public function apiIndex(Request $request): JsonResponse
{
return response()->json(['data' => $this->lists($request)]);
}
public function apiShow(Request $request, Poll $poll): JsonResponse
{
$this->ensureVisible($request, $poll);
return response()->json(['data' => Presenter::present($poll, $request->user())]);
}
/**
* @return array{open: list<array<string, mixed>>, closed: list<array<string, mixed>>}
*/
private function lists(Request $request): array
{
$user = $request->user();
$voted = fn (Poll $poll) => [...Presenter::card($poll), 'voted' => $poll->hasVoted($user)];
return [
'open' => Poll::query()->open()->visibleTo($user)->orderByRaw('closes_at IS NULL')->orderBy('closes_at')->latest('published_at')->limit(50)->get()->map($voted)->all(),
'closed' => Poll::query()->published()->whereNotNull('closes_at')->where('closes_at', '<=', now())->visibleTo($user)->latest('closes_at')->limit(30)->get()->map($voted)->all(),
];
}
private function ensureVisible(Request $request, Poll $poll): void
{
$user = $request->user();
abort_unless(($poll->isPublished() || $user->can('polls.manage')) && $poll->isVisibleTo($user), 404);
}
}

View file

@ -0,0 +1,181 @@
<?php
namespace Inhaus\Plugins\Umfragen\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Support\Audit;
use App\Support\Csv;
use App\Support\Permissions\Audiences;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Umfragen\Announcer;
use Inhaus\Plugins\Umfragen\Models\Poll;
use Inhaus\Plugins\Umfragen\Questions;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Umfragen im Portal anlegen und auswerten (Recht „polls.manage“).
*/
class PollEditorController extends Controller
{
public function create(): Response
{
Gate::authorize('polls.manage');
return $this->editor(null);
}
public function edit(Poll $poll): Response
{
Gate::authorize('polls.manage');
return $this->editor($poll);
}
public function store(Request $request): RedirectResponse
{
Gate::authorize('polls.manage');
[$attributes, $audience] = $this->validated($request, null);
$poll = Poll::query()->create([...$attributes, 'author_id' => $request->user()->id]);
Audiences::sync('poll', $poll->id, $audience);
Audit::log('poll.created', ['poll' => $poll->id, 'title' => $poll->title]);
app(Announcer::class)->announceIfDue($poll);
return to_route($poll->published_at ? 'polls.show' : 'polls.edit', $poll)->with('status', 'Umfrage gespeichert.');
}
public function update(Request $request, Poll $poll): RedirectResponse
{
Gate::authorize('polls.manage');
[$attributes, $audience] = $this->validated($request, $poll);
$poll->update($attributes);
Audiences::sync('poll', $poll->id, $audience);
Audit::log('poll.updated', ['poll' => $poll->id, 'title' => $poll->title]);
app(Announcer::class)->announceIfDue($poll);
return back()->with('status', 'Umfrage gespeichert.');
}
public function destroy(Poll $poll): RedirectResponse
{
Gate::authorize('polls.manage');
$poll->delete();
Audiences::sync('poll', $poll->id, []);
Audit::log('poll.deleted', ['poll' => $poll->id, 'title' => $poll->title]);
return to_route('polls.index')->with('status', 'Umfrage „'.$poll->title.'“ gelöscht.');
}
public function export(Poll $poll): StreamedResponse
{
Gate::authorize('polls.manage');
$questions = $poll->questions;
$labels = fn (array $question, mixed $value) => match ($question['type']) {
'single', 'multiple' => collect($question['options'])->whereIn('id', (array) $value)->pluck('label')->implode(', '),
default => (string) $value,
};
return response()->streamDownload(function () use ($poll, $questions, $labels) {
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, [...($poll->anonymous ? [] : ['Name']), 'Datum', ...array_column($questions, 'label')], ';');
$poll->responses()->with('user')->orderBy('id')->chunk(500, function ($responses) use ($out, $poll, $questions, $labels) {
foreach ($responses as $response) {
fputcsv($out, array_map(Csv::cell(...), [
...($poll->anonymous ? [] : [$response->user?->name ?? '(gelöscht)']),
$response->submitted_on?->format('d.m.Y'),
...array_map(fn ($q) => isset($response->answers[$q['id']]) ? $labels($q, $response->answers[$q['id']]) : '', $questions),
]), ';');
}
});
fclose($out);
}, 'umfrage-'.$poll->id.'.csv', ['Content-Type' => 'text/csv; charset=utf-8']);
}
private function editor(?Poll $poll): Response
{
return Inertia::render('umfragen::Editor', [
'poll' => $poll ? [
'id' => $poll->id,
'title' => $poll->title,
'description' => $poll->description,
'questions' => $poll->questions,
'anonymous' => $poll->anonymous,
'results_visibility' => $poll->results_visibility,
'published' => $poll->published_at !== null,
'published_at' => $poll->published_at?->format('Y-m-d\TH:i'),
'closes_at' => $poll->closes_at?->format('Y-m-d\TH:i'),
'announce' => $poll->announce,
'announced' => $poll->announced_at !== null,
'responses' => $poll->responses()->count(),
'audience' => Audiences::get('poll', $poll->id),
'url' => route('polls.show', $poll),
] : null,
'visibilityOptions' => Poll::VISIBILITY,
'audienceOptions' => Audiences::options(),
]);
}
/**
* @return array{0: array<string, mixed>, 1: array<string, list<string>>}
*/
private function validated(Request $request, ?Poll $poll): array
{
$data = $request->validate([
'title' => ['required', 'string', 'max:200'],
'description' => ['nullable', 'string', 'max:5000'],
'questions' => ['required', 'array', 'max:'.Questions::MAX_QUESTIONS],
'anonymous' => ['boolean'],
'results_visibility' => ['required', Rule::in(array_keys(Poll::VISIBILITY))],
'published' => ['boolean'],
'published_at' => ['nullable', 'date'],
'closes_at' => ['nullable', 'date'],
'announce' => ['boolean'],
'audience' => ['nullable', 'array'],
'audience.*' => ['array'],
'audience.*.*' => ['string', 'max:150'],
], [], ['title' => 'Titel', 'closes_at' => 'Ende', 'published_at' => 'Beginn']);
$questions = Questions::sanitize($data['questions']);
if ($questions === []) {
throw ValidationException::withMessages(['questions' => 'Bitte mindestens eine vollständige Frage anlegen (Auswahlfragen mit mindestens zwei Antworten).']);
}
$published = (bool) ($data['published'] ?? false);
$publishedAt = $published ? (filled($data['published_at'] ?? null) ? Carbon::parse($data['published_at']) : ($poll?->published_at ?? now())) : null;
$closesAt = filled($data['closes_at'] ?? null) ? Carbon::parse($data['closes_at']) : null;
if ($closesAt && $publishedAt && $closesAt->lte($publishedAt)) {
throw ValidationException::withMessages(['closes_at' => 'Das Ende muss nach dem Beginn liegen.']);
}
// Anonym lässt sich nach den ersten Stimmen nicht mehr ändern – sonst wären Namen nachträglich weg oder zu Unrecht versprochen
$anonymous = (bool) ($data['anonymous'] ?? false);
if ($poll && $poll->anonymous !== $anonymous && $poll->responses()->exists()) {
throw ValidationException::withMessages(['anonymous' => 'Nach den ersten Stimmen lässt sich „Anonym“ nicht mehr ändern.']);
}
return [[
'title' => trim($data['title']),
'description' => filled($data['description'] ?? null) ? trim($data['description']) : null,
'questions' => $questions,
'anonymous' => $anonymous,
'results_visibility' => $data['results_visibility'],
'published_at' => $publishedAt,
'closes_at' => $closesAt,
'announce' => (bool) ($data['announce'] ?? false),
], array_intersect_key((array) ($data['audience'] ?? []), array_flip(['role', 'department', 'location', 'exclude_role']))];
}
}

View file

@ -0,0 +1,127 @@
<?php
namespace Inhaus\Plugins\Umfragen\Models;
use App\Models\User;
use App\Support\Permissions\Audiences;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([
'title', 'description', 'questions', 'anonymous', 'results_visibility',
'published_at', 'closes_at', 'announce', 'author_id',
])]
class Poll extends Model
{
public const AFTER_VOTE = 'after_vote';
public const AFTER_END = 'after_end';
public const EDITORS = 'editors';
public const VISIBILITY = [
self::AFTER_VOTE => 'Nach der eigenen Abstimmung',
self::AFTER_END => 'Erst nach dem Ende der Umfrage',
self::EDITORS => 'Nur für die Redaktion',
];
protected function casts(): array
{
return [
'questions' => 'array',
'anonymous' => 'boolean',
'announce' => 'boolean',
'published_at' => 'datetime',
'closes_at' => 'datetime',
'announced_at' => 'datetime',
];
}
/**
* @return HasMany<PollResponse, $this>
*/
public function responses(): HasMany
{
return $this->hasMany(PollResponse::class);
}
/**
* @return BelongsTo<User, $this>
*/
public function author(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function isPublished(): bool
{
return $this->published_at !== null && $this->published_at->lte(now());
}
public function isClosed(): bool
{
return $this->closes_at !== null && $this->closes_at->lte(now());
}
public function isOpen(): bool
{
return $this->isPublished() && ! $this->isClosed();
}
public function status(): string
{
return match (true) {
$this->published_at === null => 'draft',
! $this->isPublished() => 'scheduled',
$this->isClosed() => 'closed',
default => 'open',
};
}
/**
* @param Builder<Poll> $query
*/
public function scopePublished(Builder $query): void
{
$query->whereNotNull('published_at')->where('published_at', '<=', now());
}
/**
* @param Builder<Poll> $query
*/
public function scopeOpen(Builder $query): void
{
$query->published()->where(fn (Builder $q) => $q->whereNull('closes_at')->orWhere('closes_at', '>', now()));
}
/**
* @param Builder<Poll> $query
*/
public function scopeVisibleTo(Builder $query, ?User $user): void
{
if ($user?->can('polls.manage')) {
return;
}
Audiences::constrain($query, 'poll', 'polls.id', $user);
}
public function isVisibleTo(?User $user): bool
{
return (bool) $user?->can('polls.manage') || Audiences::allows('poll', $this->id, $user);
}
/** Schlüssel je Person und Umfrage – verhindert doppelte Stimmen, verrät die Person nicht */
public function voterKey(User $user): string
{
return hash_hmac('sha256', 'poll:'.$this->id.':'.$user->id, (string) config('app.key'));
}
public function hasVoted(User $user): bool
{
return $this->responses()->where('voter', $this->voterKey($user))->exists();
}
}

View file

@ -0,0 +1,27 @@
<?php
namespace Inhaus\Plugins\Umfragen\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['poll_id', 'user_id', 'voter', 'answers', 'submitted_on'])]
class PollResponse extends Model
{
public $timestamps = false;
protected function casts(): array
{
return ['answers' => 'array', 'submitted_on' => 'date'];
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}

View file

@ -0,0 +1,60 @@
<?php
namespace Inhaus\Plugins\Umfragen;
use App\Models\User;
use Inhaus\Plugins\Umfragen\Models\Poll;
/**
* Umfrage für die Anzeige (Seite, Baustein, App) – mit dem Stand für diese Person.
*/
class Presenter
{
/**
* @return array<string, mixed>
*/
public static function present(Poll $poll, User $user): array
{
$editor = $user->can('polls.manage');
$voted = $poll->hasVoted($user);
$visible = $editor || match ($poll->results_visibility) {
Poll::EDITORS => false,
Poll::AFTER_END => $poll->isClosed(),
default => $voted || $poll->isClosed(),
};
return [
...self::card($poll),
'description' => $poll->description,
'questions' => $poll->questions,
'anonymous' => $poll->anonymous,
'voted' => $voted,
'can_vote' => $poll->isOpen() && ! $voted,
'results' => $visible ? app(Results::class)->for($poll, $editor) : null,
'results_note' => $visible ? null : match ($poll->results_visibility) {
Poll::EDITORS => 'Die Ergebnisse wertet die Redaktion aus.',
Poll::AFTER_END => $poll->closes_at ? 'Die Ergebnisse erscheinen nach dem Ende der Umfrage am '.$poll->closes_at->timezone(config('app.timezone'))->format('d.m.Y, H:i').' Uhr.' : 'Die Ergebnisse erscheinen nach dem Ende der Umfrage.',
default => 'Die Ergebnisse sehen Sie nach Ihrer Abstimmung.',
},
'edit_url' => $editor ? route('polls.edit', $poll) : null,
'export_url' => $editor ? route('polls.export', $poll) : null,
];
}
/**
* @return array<string, mixed>
*/
public static function card(Poll $poll): array
{
return [
'id' => $poll->id,
'title' => $poll->title,
'status' => $poll->status(),
'open' => $poll->isOpen(),
'closes_at' => $poll->closes_at?->toIso8601String(),
'published_at' => $poll->published_at?->toIso8601String(),
'questions_count' => count($poll->questions ?? []),
'url' => route('polls.show', $poll),
];
}
}

View file

@ -0,0 +1,135 @@
<?php
namespace Inhaus\Plugins\Umfragen;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
/**
* Fragen einer Umfrage: bereinigen (Editor) und Antworten prüfen (Abstimmung).
*
* [{"id": "q1ab", "type": "single|multiple|scale|text", "label": "…", "required": true,
* "options": [{"id": "o1", "label": "…"}], "max": 2, "scale": 5, "min_label": "…", "max_label": "…"}]
*/
class Questions
{
public const TYPES = ['single', 'multiple', 'scale', 'text'];
public const MAX_QUESTIONS = 30;
/**
* @return list<array<string, mixed>>
*/
public static function sanitize(mixed $questions): array
{
$result = [];
foreach (array_slice(array_values(is_array($questions) ? $questions : []), 0, self::MAX_QUESTIONS) as $question) {
if (! is_array($question) || ! in_array($question['type'] ?? null, self::TYPES, true)) {
continue;
}
$label = mb_substr(trim((string) ($question['label'] ?? '')), 0, 300);
if ($label === '') {
continue;
}
$clean = [
'id' => self::id($question['id'] ?? null),
'type' => $question['type'],
'label' => $label,
'required' => (bool) ($question['required'] ?? true),
];
if (in_array($clean['type'], ['single', 'multiple'], true)) {
$options = [];
foreach (array_slice(array_values((array) ($question['options'] ?? [])), 0, 20) as $option) {
$text = mb_substr(trim((string) (is_array($option) ? ($option['label'] ?? '') : $option)), 0, 200);
if ($text !== '') {
$options[] = ['id' => self::id(is_array($option) ? ($option['id'] ?? null) : null), 'label' => $text];
}
}
if (count($options) < 2) {
continue;
}
$clean['options'] = $options;
if ($clean['type'] === 'multiple') {
$max = (int) ($question['max'] ?? 0);
$clean['max'] = $max >= 1 && $max < count($options) ? $max : null;
}
}
if ($clean['type'] === 'scale') {
$clean['scale'] = in_array((int) ($question['scale'] ?? 5), [5, 10], true) ? (int) $question['scale'] : 5;
$clean['min_label'] = mb_substr(trim((string) ($question['min_label'] ?? '')), 0, 60) ?: null;
$clean['max_label'] = mb_substr(trim((string) ($question['max_label'] ?? '')), 0, 60) ?: null;
}
$result[] = $clean;
}
return $result;
}
/**
* Antworten gegen die Fragen prüfen.
*
* @param list<array<string, mixed>> $questions
* @return array<string, mixed>
*/
public static function validate(array $questions, mixed $answers): array
{
$answers = is_array($answers) ? $answers : [];
$clean = [];
$errors = [];
foreach ($questions as $question) {
$value = $answers[$question['id']] ?? null;
$key = 'answers.'.$question['id'];
$value = match ($question['type']) {
'single' => in_array($value, array_column($question['options'], 'id'), true) ? $value : null,
'multiple' => array_values(array_intersect(array_column($question['options'], 'id'), array_filter((array) $value, 'is_string'))) ?: null,
'scale' => is_numeric($value) && (int) $value >= 1 && (int) $value <= $question['scale'] ? (int) $value : null,
'text' => is_string($value) && trim($value) !== '' ? mb_substr(trim($value), 0, 2000) : null,
};
if ($value === null) {
if ($question['required']) {
$errors[$key] = 'Bitte beantworten Sie diese Frage.';
}
continue;
}
if ($question['type'] === 'multiple' && ($question['max'] ?? null) && count($value) > $question['max']) {
$errors[$key] = "Bitte höchstens {$question['max']} auswählen.";
continue;
}
$clean[$question['id']] = $value;
}
if ($errors !== []) {
throw ValidationException::withMessages($errors);
}
if ($clean === []) {
throw ValidationException::withMessages(['answers' => 'Bitte beantworten Sie mindestens eine Frage.']);
}
return $clean;
}
private static function id(mixed $id): string
{
return is_string($id) && preg_match('/^[A-Za-z0-9_-]{2,20}$/', $id) ? $id : Str::lower(Str::random(8));
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace Inhaus\Plugins\Umfragen;
use Inhaus\Plugins\Umfragen\Models\Poll;
/**
* Auswertung einer Umfrage je Frage.
*/
class Results
{
/**
* @return array{total: int, questions: list<array<string, mixed>>}
*/
public function for(Poll $poll, bool $withTexts): array
{
$answers = $poll->responses()->pluck('answers')->map(fn ($a) => is_array($a) ? $a : (json_decode((string) $a, true) ?: []));
$total = $answers->count();
return [
'total' => $total,
'questions' => collect($poll->questions)->map(function (array $question) use ($answers, $withTexts) {
$given = $answers->map(fn ($a) => $a[$question['id']] ?? null)->filter(fn ($v) => $v !== null && $v !== []);
$count = $given->count();
$result = ['id' => $question['id'], 'type' => $question['type'], 'label' => $question['label'], 'answered' => $count];
if (in_array($question['type'], ['single', 'multiple'], true)) {
$tally = $given->flatMap(fn ($v) => (array) $v)->countBy();
$result['options'] = collect($question['options'])->map(fn ($o) => [
'id' => $o['id'],
'label' => $o['label'],
'votes' => (int) ($tally[$o['id']] ?? 0),
'percent' => $count ? (int) round(($tally[$o['id']] ?? 0) / $count * 100) : 0,
])->all();
}
if ($question['type'] === 'scale') {
$tally = $given->countBy();
$result['scale'] = $question['scale'];
$result['min_label'] = $question['min_label'] ?? null;
$result['max_label'] = $question['max_label'] ?? null;
$result['average'] = $count ? round($given->avg(), 1) : null;
$result['distribution'] = collect(range(1, $question['scale']))->map(fn ($n) => ['value' => $n, 'votes' => (int) ($tally[$n] ?? 0)])->all();
}
if ($question['type'] === 'text') {
// Freitexte nur für die Redaktion – sie können Rückschlüsse auf Personen erlauben
$result['texts'] = $withTexts ? $given->values()->shuffle()->take(500)->values()->all() : null;
}
return $result;
})->all(),
];
}
}

View file

@ -0,0 +1,57 @@
<?php
namespace Inhaus\Plugins\Umfragen;
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;
use Illuminate\Support\Facades\Schedule;
use Inhaus\Plugins\Umfragen\Models\Poll;
class UmfragenPlugin extends Plugin
{
public function register(): void
{
$this->app->make(Navigation::class)->add('umfragen', 'Umfragen', '/umfragen', active: 'polls.*', sort: 74);
$this->app->make(Abilities::class)->define('polls.manage', 'Umfragen anlegen und auswerten', 'Umfragen', portal: true);
$this->app->make(Editorial::class)->add('umfragen', 'Umfragen', 'umfragen::EditorialPolls', 32,
fn (User $user) => $user->can('polls.manage'),
fn (User $user) => [
'polls' => Poll::query()->withCount('responses')->orderByRaw('published_at IS NULL DESC')->latest('published_at')->latest('id')->limit(50)->get()
->map(fn (Poll $poll) => [...Presenter::card($poll), 'responses' => $poll->responses_count, 'edit_url' => route('polls.edit', $poll)])->all(),
]);
// Startseite: offene Umfragen, an denen die Person noch nicht teilgenommen hat
$this->app->make(Widgets::class)->add('umfragen.open', 'umfragen::Open', 'aside', sort: 25, props: function (User $user) {
$polls = Poll::query()->open()->visibleTo($user)->latest('published_at')->limit(10)->get()
->reject(fn (Poll $poll) => $poll->hasVoted($user))->take(3);
return $polls->isEmpty() ? null : ['polls' => $polls->map(fn (Poll $poll) => Presenter::card($poll))->values()->all()];
}, label: 'Offene Umfragen', mobileSort: 35);
// Baustein: Umfrage direkt in Seite oder Beitrag
$this->app->make(Blocks::class)->add(BlockType::make('umfragen.poll', 'Umfrage', 'vote', 'dynamic', 'umfragen::PollBlock')
->description('Eine Umfrage direkt auf der Seite beantworten lassen.')
->fields([
Field::select('poll', 'Umfrage', fn () => Poll::query()->latest('id')->limit(200)->pluck('title', 'id')->mapWithKeys(fn ($t, $id) => [(string) $id => $t])->all()),
])
->resolveUsing(function (array $data, ?User $user) {
$poll = $data['poll'] ? Poll::query()->find($data['poll']) : null;
return $poll && $user && ($poll->isPublished() || $user->can('polls.manage')) && $poll->isVisibleTo($user) ? Presenter::present($poll, $user) : null;
}));
}
public function boot(): void
{
// Geplante Umfragen ankündigen, sobald sie beginnen
Schedule::call(fn () => $this->app->make(Announcer::class)->announceDue())->everyTenMinutes()->name('umfragen-announce')->withoutOverlapping(10);
}
}