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
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:
parent
08953d52cb
commit
3f67fde50b
153 changed files with 2075 additions and 329 deletions
|
|
@ -0,0 +1,48 @@
|
|||
<?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('polls', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('title');
|
||||
$table->text('description')->nullable();
|
||||
$table->json('questions');
|
||||
$table->boolean('anonymous')->default(false);
|
||||
// after_vote | after_end | editors
|
||||
$table->string('results_visibility', 20)->default('after_vote');
|
||||
$table->timestamp('published_at')->nullable();
|
||||
$table->timestamp('closes_at')->nullable();
|
||||
$table->timestamp('announced_at')->nullable();
|
||||
$table->boolean('announce')->default(false);
|
||||
$table->foreignId('author_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['published_at', 'closes_at']);
|
||||
});
|
||||
|
||||
// Anonyme Umfragen: keine Person, nur ein nicht umkehrbarer Schlüssel gegen doppelte Stimmen
|
||||
// und nur das Datum (keine Uhrzeit, die sich mit Protokollen abgleichen ließe).
|
||||
Schema::create('poll_responses', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('poll_id')->constrained('polls')->cascadeOnDelete();
|
||||
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
|
||||
$table->char('voter', 64);
|
||||
$table->json('answers');
|
||||
$table->date('submitted_on');
|
||||
|
||||
$table->unique(['poll_id', 'voter']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('poll_responses');
|
||||
Schema::dropIfExists('polls');
|
||||
}
|
||||
};
|
||||
14
plugins-core/umfragen/plugin.json
Normal file
14
plugins-core/umfragen/plugin.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"slug": "umfragen",
|
||||
"name": "Umfragen",
|
||||
"version": "1.0.0",
|
||||
"description": "Umfragen und Abstimmungen mit Einfach- und Mehrfachauswahl, Skala und Freitext – für Zielgruppen, auf Wunsch anonym. Ergebnisse je Umfrage nach der Abstimmung, nach dem Ende oder nur für die Redaktion sichtbar.",
|
||||
"author": "Inhaus",
|
||||
"namespace": "Inhaus\\Plugins\\Umfragen\\",
|
||||
"class": "Inhaus\\Plugins\\Umfragen\\UmfragenPlugin",
|
||||
"enabled_by_default": false,
|
||||
"requires": {
|
||||
"core": ">=0.31.0",
|
||||
"php": ">=8.3"
|
||||
}
|
||||
}
|
||||
19
plugins-core/umfragen/resources/js/blocks/PollBlock.vue
Normal file
19
plugins-core/umfragen/resources/js/blocks/PollBlock.vue
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
<script setup>
|
||||
import { inject } from 'vue';
|
||||
import { Vote } from '@lucide/vue';
|
||||
import PollForm from '../components/PollForm.vue';
|
||||
|
||||
defineProps({ block: { type: Object, required: true } });
|
||||
|
||||
const editing = inject('pagebuilder:editing', false);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section v-if="block.props" class="rounded-lg border bg-card p-5 @3xl:p-8">
|
||||
<p class="mb-1 flex items-center gap-1.5 text-xs font-semibold tracking-wider text-brand-text uppercase"><Vote class="size-3.5" /> Umfrage</p>
|
||||
<h3 class="text-xl font-semibold tracking-tight">{{ block.props.title }}</h3>
|
||||
<p v-if="block.props.description" class="mt-2 text-sm leading-relaxed whitespace-pre-line text-muted-foreground">{{ block.props.description }}</p>
|
||||
<PollForm :key="block.props.id" :poll="block.props" :disabled="editing" compact class="mt-6" />
|
||||
</section>
|
||||
<p v-else-if="editing" class="rounded-lg border border-dashed p-4 text-sm text-muted-foreground">Bitte rechts eine Umfrage auswählen.</p>
|
||||
</template>
|
||||
116
plugins-core/umfragen/resources/js/components/PollForm.vue
Normal file
116
plugins-core/umfragen/resources/js/components/PollForm.vue
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import { useForm } from '@inertiajs/vue3';
|
||||
import { CircleCheck, LoaderCircle, Lock } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import PollResults from './PollResults.vue';
|
||||
|
||||
/**
|
||||
* Umfrage beantworten – oder, nach der Abstimmung, die Ergebnisse bzw. einen Hinweis.
|
||||
*/
|
||||
const props = defineProps({
|
||||
poll: { type: Object, required: true },
|
||||
compact: { type: Boolean, default: false },
|
||||
disabled: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const form = useForm({
|
||||
answers: Object.fromEntries(props.poll.questions.map((q) => [q.id, q.type === 'multiple' ? [] : null])),
|
||||
});
|
||||
|
||||
function toggle(question, optionId) {
|
||||
const list = form.answers[question.id];
|
||||
const index = list.indexOf(optionId);
|
||||
|
||||
if (index >= 0) list.splice(index, 1);
|
||||
else if (!question.max || list.length < question.max) list.push(optionId);
|
||||
}
|
||||
|
||||
const complete = computed(() => props.poll.questions.every((q) => {
|
||||
const value = form.answers[q.id];
|
||||
|
||||
return !q.required || (Array.isArray(value) ? value.length : value !== null && value !== '');
|
||||
}));
|
||||
|
||||
function submit() {
|
||||
form.post(`/umfragen/${props.poll.id}/abstimmen`, { preserveScroll: true });
|
||||
}
|
||||
|
||||
const firstError = computed(() => form.errors.answers ?? null);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<form v-if="poll.can_vote" class="grid gap-6" @submit.prevent="submit">
|
||||
<fieldset v-for="(question, index) in poll.questions" :key="question.id" class="grid gap-2.5" :disabled="disabled">
|
||||
<legend class="mb-2.5 text-sm font-semibold">
|
||||
<span v-if="poll.questions.length > 1" class="text-muted-foreground">{{ index + 1 }}. </span>{{ question.label }}
|
||||
<span v-if="!question.required" class="font-normal text-muted-foreground"> (optional)</span>
|
||||
<span v-if="question.type === 'multiple'" class="block text-xs font-normal text-muted-foreground">{{ question.max ? `Bis zu ${question.max} Antworten` : 'Mehrere Antworten möglich' }}</span>
|
||||
</legend>
|
||||
|
||||
<template v-if="question.type === 'single' || question.type === 'multiple'">
|
||||
<label
|
||||
v-for="option in question.options"
|
||||
:key="option.id"
|
||||
class="flex cursor-pointer items-center gap-3 rounded-md border px-3.5 py-2.5 text-sm transition-colors hover:bg-accent/50 has-[:checked]:border-brand has-[:checked]:bg-brand-soft"
|
||||
>
|
||||
<input
|
||||
v-if="question.type === 'single'"
|
||||
v-model="form.answers[question.id]"
|
||||
type="radio"
|
||||
:name="`q-${poll.id}-${question.id}`"
|
||||
:value="option.id"
|
||||
class="size-4 accent-[var(--color-brand)]"
|
||||
/>
|
||||
<input
|
||||
v-else
|
||||
type="checkbox"
|
||||
:checked="form.answers[question.id].includes(option.id)"
|
||||
class="size-4 accent-[var(--color-brand)]"
|
||||
@change="toggle(question, option.id)"
|
||||
/>
|
||||
{{ option.label }}
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<div v-else-if="question.type === 'scale'" class="grid gap-1.5">
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<label
|
||||
v-for="n in question.scale"
|
||||
:key="n"
|
||||
class="grid size-10 cursor-pointer place-items-center rounded-md border text-sm font-medium tabular-nums transition-colors hover:bg-accent/50 has-[:checked]:border-brand has-[:checked]:bg-brand has-[:checked]:text-brand-foreground"
|
||||
>
|
||||
<input v-model="form.answers[question.id]" type="radio" :name="`q-${poll.id}-${question.id}`" :value="n" class="sr-only" />
|
||||
{{ n }}
|
||||
</label>
|
||||
</div>
|
||||
<div v-if="question.min_label || question.max_label" class="flex justify-between gap-3 text-xs text-muted-foreground" :style="{ maxWidth: `${question.scale * 2.5 + (question.scale - 1) * 0.375}rem` }">
|
||||
<span>1 = {{ question.min_label }}</span><span>{{ question.scale }} = {{ question.max_label }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Textarea v-else v-model="form.answers[question.id]" rows="3" maxlength="2000" />
|
||||
|
||||
<p v-if="form.errors[`answers.${question.id}`]" class="text-[13px] text-destructive">{{ form.errors[`answers.${question.id}`] }}</p>
|
||||
</fieldset>
|
||||
|
||||
<p v-if="firstError" class="text-[13px] text-destructive">{{ firstError }}</p>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<Button type="submit" :disabled="form.processing || !complete || disabled">
|
||||
<LoaderCircle v-if="form.processing" class="animate-spin" />
|
||||
Abstimmen
|
||||
</Button>
|
||||
<span v-if="poll.anonymous" class="inline-flex items-center gap-1.5 text-xs text-muted-foreground"><Lock class="size-3.5" /> Anonym – Ihre Antworten werden ohne Namen gespeichert.</span>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<template v-else>
|
||||
<p v-if="poll.voted" class="mb-5 flex items-center gap-2 text-sm font-medium text-brand-text"><CircleCheck class="size-4" /> Sie haben teilgenommen – danke!</p>
|
||||
<p v-else-if="!poll.open" class="mb-5 text-sm text-muted-foreground">Diese Umfrage ist beendet.</p>
|
||||
<PollResults v-if="poll.results" :results="poll.results" :compact="compact" />
|
||||
<p v-else-if="poll.results_note" class="text-sm text-muted-foreground">{{ poll.results_note }}</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
<script setup>
|
||||
/**
|
||||
* Ergebnisse einer Umfrage: Balken je Antwort, Skalen mit Durchschnitt, Freitexte (nur Redaktion).
|
||||
*/
|
||||
defineProps({
|
||||
results: { type: Object, required: true },
|
||||
compact: { type: Boolean, default: false },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid gap-6">
|
||||
<p class="text-sm text-muted-foreground">{{ results.total }} {{ results.total === 1 ? 'Teilnahme' : 'Teilnahmen' }}</p>
|
||||
<section v-for="(question, index) in results.questions" :key="question.id" class="grid gap-3">
|
||||
<h3 class="text-sm font-semibold"><span v-if="results.questions.length > 1" class="text-muted-foreground">{{ index + 1 }}. </span>{{ question.label }}</h3>
|
||||
|
||||
<ul v-if="question.options" class="grid gap-2.5">
|
||||
<li v-for="option in question.options" :key="option.id" class="grid gap-1">
|
||||
<div class="flex items-baseline justify-between gap-3 text-sm">
|
||||
<span class="min-w-0">{{ option.label }}</span>
|
||||
<span class="shrink-0 text-muted-foreground tabular-nums">{{ option.percent }} %<span v-if="!compact" class="text-xs"> · {{ option.votes }}</span></span>
|
||||
</div>
|
||||
<div class="h-2 overflow-hidden rounded-full bg-muted">
|
||||
<div class="h-full rounded-full bg-brand transition-[width] duration-500" :style="{ width: `${option.percent}%` }" />
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div v-else-if="question.type === 'scale'" class="grid gap-2">
|
||||
<p class="text-sm">Durchschnitt: <span class="font-semibold tabular-nums">{{ question.average === null ? '–' : question.average.toLocaleString('de-DE') }}</span> <span class="text-muted-foreground">von {{ question.scale }}</span></p>
|
||||
<div class="flex h-20 items-end gap-1" role="img" :aria-label="`Verteilung der Antworten von 1 bis ${question.scale}`">
|
||||
<div v-for="bar in question.distribution" :key="bar.value" class="flex flex-1 flex-col items-center gap-1">
|
||||
<div class="w-full rounded-t-sm bg-brand/75" :style="{ height: `${question.answered ? Math.max(3, (bar.votes / Math.max(...question.distribution.map((d) => d.votes), 1)) * 56) : 3}px` }" :title="`${bar.value}: ${bar.votes}`" />
|
||||
<span class="text-[11px] text-muted-foreground tabular-nums">{{ bar.value }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="question.min_label || question.max_label" class="flex justify-between text-[11px] text-muted-foreground">
|
||||
<span>{{ question.min_label }}</span><span>{{ question.max_label }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-else-if="question.type === 'text'">
|
||||
<p class="text-sm text-muted-foreground">{{ question.answered }} {{ question.answered === 1 ? 'Antwort' : 'Antworten' }}</p>
|
||||
<ul v-if="question.texts?.length" class="grid max-h-80 gap-2 overflow-y-auto">
|
||||
<li v-for="(text, i) in question.texts" :key="i" class="rounded-md bg-muted/60 px-3 py-2 text-sm whitespace-pre-line">{{ text }}</li>
|
||||
</ul>
|
||||
</template>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { Plus, Users } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import { formatShortDate } from '@/lib/format';
|
||||
|
||||
defineProps({
|
||||
polls: { type: Array, required: true },
|
||||
});
|
||||
|
||||
const statuses = {
|
||||
open: ['Läuft', 'bg-brand-soft text-brand-text'],
|
||||
draft: ['Entwurf', 'bg-muted text-muted-foreground'],
|
||||
scheduled: ['Geplant', 'bg-accent text-accent-foreground'],
|
||||
closed: ['Beendet', 'bg-muted text-muted-foreground'],
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Panel title="Umfragen">
|
||||
<template #actions>
|
||||
<Button size="sm" variant="outline" as-child><Link href="/redaktion/umfragen/neu"><Plus /> Neue Umfrage</Link></Button>
|
||||
</template>
|
||||
<ul v-if="polls.length" class="-mx-5 divide-y border-t">
|
||||
<li v-for="poll in polls" :key="poll.id" class="flex items-center gap-3 px-5 py-2.5">
|
||||
<div class="min-w-0 flex-1">
|
||||
<Link :href="poll.edit_url" class="block truncate text-sm font-medium hover:underline">{{ poll.title }}</Link>
|
||||
<p class="truncate text-xs text-muted-foreground">{{ poll.questions_count }} {{ poll.questions_count === 1 ? 'Frage' : 'Fragen' }}<template v-if="poll.closes_at"> · bis {{ formatShortDate(poll.closes_at) }}</template></p>
|
||||
</div>
|
||||
<Link :href="poll.url" class="inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground hover:text-foreground" :title="`${poll.responses} Teilnahmen – Ergebnisse ansehen`"><Users class="size-3.5" /> {{ poll.responses }}</Link>
|
||||
<span class="shrink-0 rounded px-1.5 py-0.5 text-[11px] font-medium" :class="statuses[poll.status][1]">{{ statuses[poll.status][0] }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="text-sm text-muted-foreground">Noch keine Umfragen.</p>
|
||||
</Panel>
|
||||
</template>
|
||||
212
plugins-core/umfragen/resources/js/pages/Editor.vue
Normal file
212
plugins-core/umfragen/resources/js/pages/Editor.vue
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
<script setup>
|
||||
import { computed, watch } from 'vue';
|
||||
import { Link, router, useForm, usePage } from '@inertiajs/vue3';
|
||||
import { ArrowDown, ArrowUp, CircleDot, ListChecks, LoaderCircle, Plus, Save, SlidersHorizontal, Trash2, TriangleAlert, Type, Users, 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 AudienceEditor from '@/components/AudienceEditor.vue';
|
||||
import FormField from '@/components/FormField.vue';
|
||||
import PageHeader from '@/components/PageHeader.vue';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
|
||||
/**
|
||||
* Umfrage anlegen oder bearbeiten (Redaktion im Portal).
|
||||
*/
|
||||
const props = defineProps({
|
||||
poll: { type: Object, default: null },
|
||||
visibilityOptions: { type: Object, required: true },
|
||||
audienceOptions: { type: Object, required: true },
|
||||
});
|
||||
|
||||
const page = usePage();
|
||||
watch(() => page.props.flash.status, (status) => status && toast.success(status), { immediate: true });
|
||||
|
||||
const uid = () => Math.random().toString(36).slice(2, 10);
|
||||
const types = {
|
||||
single: { label: 'Eine Antwort', icon: CircleDot },
|
||||
multiple: { label: 'Mehrere Antworten', icon: ListChecks },
|
||||
scale: { label: 'Skala', icon: SlidersHorizontal },
|
||||
text: { label: 'Freitext', icon: Type },
|
||||
};
|
||||
|
||||
const p = props.poll;
|
||||
const form = useForm({
|
||||
title: p?.title ?? '',
|
||||
description: p?.description ?? '',
|
||||
questions: p?.questions?.map((q) => ({ ...q, options: q.options?.map((o) => ({ ...o })) })) ?? [
|
||||
{ id: uid(), type: 'single', label: '', required: true, options: [{ id: uid(), label: '' }, { id: uid(), label: '' }] },
|
||||
],
|
||||
anonymous: p?.anonymous ?? false,
|
||||
results_visibility: p?.results_visibility ?? 'after_vote',
|
||||
published: p?.published ?? false,
|
||||
published_at: p?.published_at ?? '',
|
||||
closes_at: p?.closes_at ?? '',
|
||||
announce: p?.announce ?? false,
|
||||
audience: p?.audience ?? {},
|
||||
});
|
||||
|
||||
function addQuestion(type) {
|
||||
const question = { id: uid(), type, label: '', required: true };
|
||||
|
||||
if (type === 'single' || type === 'multiple') question.options = [{ id: uid(), label: '' }, { id: uid(), label: '' }];
|
||||
if (type === 'multiple') question.max = null;
|
||||
if (type === 'scale') Object.assign(question, { scale: 5, min_label: 'gar nicht', max_label: 'sehr' });
|
||||
if (type === 'text') question.required = false;
|
||||
|
||||
form.questions.push(question);
|
||||
}
|
||||
|
||||
function move(index, delta) {
|
||||
const list = form.questions;
|
||||
const [item] = list.splice(index, 1);
|
||||
list.splice(index + delta, 0, item);
|
||||
}
|
||||
|
||||
const restricted = computed(() => Object.values(form.audience ?? {}).some((values) => values?.length));
|
||||
const hasVotes = computed(() => (p?.responses ?? 0) > 0);
|
||||
|
||||
function submit() {
|
||||
const options = { preserveScroll: true };
|
||||
p ? form.put(`/redaktion/umfragen/${p.id}`, options) : form.post('/redaktion/umfragen', options);
|
||||
}
|
||||
|
||||
function remove() {
|
||||
if (window.confirm(`Umfrage „${p.title}“ samt ${p.responses} Teilnahmen löschen?`)) {
|
||||
router.delete(`/redaktion/umfragen/${p.id}`);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout :title="p ? `Bearbeiten: ${p.title}` : 'Neue Umfrage'">
|
||||
<PageHeader :title="p ? 'Umfrage bearbeiten' : 'Neue Umfrage'" :breadcrumbs="[{ label: 'Umfragen', href: '/umfragen' }]">
|
||||
<template #actions>
|
||||
<Button v-if="p" variant="ghost" class="text-destructive hover:text-destructive" @click="remove"><Trash2 /> Löschen</Button>
|
||||
<Button v-if="p" variant="outline" as-child><Link :href="p.url">{{ p.published ? 'Ansehen & Ergebnisse' : 'Vorschau' }}</Link></Button>
|
||||
<Button :disabled="form.processing" @click="submit"><LoaderCircle v-if="form.processing" class="animate-spin" /><Save v-else /> Speichern</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<form class="grid grid-cols-1 items-start gap-6 lg:grid-cols-[minmax(0,1fr)_20rem]" @submit.prevent="submit">
|
||||
<div class="grid min-w-0 gap-6">
|
||||
<Panel>
|
||||
<div class="grid gap-5">
|
||||
<FormField id="poll-title" label="Titel bzw. Frage" :error="form.errors.title">
|
||||
<Input id="poll-title" v-model="form.title" maxlength="200" placeholder="z. B. Wie gefällt Ihnen das neue Kantinenangebot?" class="text-base" />
|
||||
</FormField>
|
||||
<FormField id="poll-description" label="Einleitung (optional)" :error="form.errors.description">
|
||||
<Textarea id="poll-description" v-model="form.description" rows="3" maxlength="5000" />
|
||||
</FormField>
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<p v-if="hasVotes" class="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 p-3 text-[13px]">
|
||||
<TriangleAlert class="mt-0.5 size-4 shrink-0 text-destructive" />
|
||||
Es gibt bereits {{ p.responses }} {{ p.responses === 1 ? 'Teilnahme' : 'Teilnahmen' }}. Tippfehler lassen sich korrigieren – neue oder entfernte Antworten verfälschen aber die Ergebnisse.
|
||||
</p>
|
||||
<p v-if="form.errors.questions" class="text-[13px] text-destructive">{{ form.errors.questions }}</p>
|
||||
|
||||
<Panel v-for="(question, index) in form.questions" :key="question.id">
|
||||
<div class="grid gap-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="inline-flex items-center gap-1.5 rounded bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground">
|
||||
<component :is="types[question.type].icon" class="size-3.5" /> Frage {{ index + 1 }} · {{ types[question.type].label }}
|
||||
</span>
|
||||
<span class="flex-1" />
|
||||
<Button type="button" variant="ghost" size="icon" class="size-8" :disabled="index === 0" aria-label="Nach oben" @click="move(index, -1)"><ArrowUp /></Button>
|
||||
<Button type="button" variant="ghost" size="icon" class="size-8" :disabled="index === form.questions.length - 1" aria-label="Nach unten" @click="move(index, 1)"><ArrowDown /></Button>
|
||||
<Button type="button" variant="ghost" size="icon" class="size-8 text-muted-foreground hover:text-destructive" :disabled="form.questions.length === 1" aria-label="Frage entfernen" @click="form.questions.splice(index, 1)"><Trash2 /></Button>
|
||||
</div>
|
||||
|
||||
<Input v-model="question.label" maxlength="300" :placeholder="form.questions.length === 1 ? 'Frage (z. B. wie der Titel)' : 'Frage'" :aria-label="`Frage ${index + 1}`" />
|
||||
|
||||
<div v-if="question.options" class="grid gap-2">
|
||||
<div v-for="(option, oi) in question.options" :key="option.id" class="flex items-center gap-2">
|
||||
<span class="w-5 text-right text-xs text-muted-foreground tabular-nums">{{ oi + 1 }}.</span>
|
||||
<Input v-model="option.label" maxlength="200" :placeholder="`Antwort ${oi + 1}`" class="h-9" :aria-label="`Antwort ${oi + 1}`" />
|
||||
<Button type="button" variant="ghost" size="icon" class="size-8 shrink-0 text-muted-foreground" :disabled="question.options.length <= 2" aria-label="Antwort entfernen" @click="question.options.splice(oi, 1)"><X /></Button>
|
||||
</div>
|
||||
<Button v-if="question.options.length < 20" type="button" variant="ghost" size="sm" class="justify-self-start" @click="question.options.push({ id: uid(), label: '' })"><Plus /> Antwort hinzufügen</Button>
|
||||
</div>
|
||||
|
||||
<div v-if="question.type === 'scale'" class="grid gap-3 sm:grid-cols-3">
|
||||
<FormField :id="`scale-${question.id}`" label="Stufen">
|
||||
<select :id="`scale-${question.id}`" v-model.number="question.scale" class="h-9 rounded-md border bg-background px-2 text-sm">
|
||||
<option :value="5">1 bis 5</option>
|
||||
<option :value="10">1 bis 10</option>
|
||||
</select>
|
||||
</FormField>
|
||||
<FormField :id="`min-${question.id}`" label="1 bedeutet"><Input :id="`min-${question.id}`" v-model="question.min_label" maxlength="60" class="h-9" /></FormField>
|
||||
<FormField :id="`max-${question.id}`" :label="`${question.scale} bedeutet`"><Input :id="`max-${question.id}`" v-model="question.max_label" maxlength="60" class="h-9" /></FormField>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-x-6 gap-y-3 border-t pt-3 text-sm">
|
||||
<label class="flex items-center gap-2"><Switch v-model="question.required" /> Pflichtfrage</label>
|
||||
<label v-if="question.type === 'multiple'" class="flex items-center gap-2">
|
||||
Höchstens
|
||||
<Input v-model.number="question.max" type="number" min="1" :max="question.options.length - 1" placeholder="alle" class="h-8 w-20" />
|
||||
Antworten
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<span class="mr-1 self-center text-sm text-muted-foreground">Frage hinzufügen:</span>
|
||||
<Button v-for="(type, key) in types" :key="key" type="button" variant="outline" size="sm" :disabled="form.questions.length >= 30" @click="addQuestion(key)">
|
||||
<component :is="type.icon" /> {{ type.label }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-6">
|
||||
<Panel title="Veröffentlichung">
|
||||
<div class="grid gap-4">
|
||||
<label class="flex items-center justify-between gap-3 text-sm">
|
||||
<span><span class="font-medium">Veröffentlicht</span><span class="block text-xs text-muted-foreground">Sonst nur für die Redaktion sichtbar.</span></span>
|
||||
<Switch v-model="form.published" />
|
||||
</label>
|
||||
<FormField v-if="form.published" id="poll-start" label="Beginn (optional)" hint="Leer = sofort." :error="form.errors.published_at">
|
||||
<Input id="poll-start" v-model="form.published_at" type="datetime-local" />
|
||||
</FormField>
|
||||
<FormField id="poll-end" label="Ende (optional)" hint="Leer = läuft, bis Sie sie beenden." :error="form.errors.closes_at">
|
||||
<Input id="poll-end" v-model="form.closes_at" type="datetime-local" />
|
||||
</FormField>
|
||||
<label class="flex items-center justify-between gap-3 text-sm">
|
||||
<span><span class="font-medium">Benachrichtigen</span><span class="block text-xs text-muted-foreground">{{ p?.announced ? 'Bereits angekündigt.' : 'Die Zielgruppe bekommt zum Start einen Hinweis.' }}</span></span>
|
||||
<Switch v-model="form.announce" :disabled="p?.announced" />
|
||||
</label>
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<Panel title="Ergebnisse & Datenschutz">
|
||||
<div class="grid gap-4">
|
||||
<FormField id="poll-visibility" label="Ergebnisse sichtbar" :error="form.errors.results_visibility">
|
||||
<select id="poll-visibility" v-model="form.results_visibility" class="h-9 w-full rounded-md border bg-background px-2 text-sm">
|
||||
<option v-for="(label, key) in visibilityOptions" :key="key" :value="key">{{ label }}</option>
|
||||
</select>
|
||||
</FormField>
|
||||
<label class="flex items-center justify-between gap-3 text-sm">
|
||||
<span><span class="font-medium">Anonym</span><span class="block text-xs text-muted-foreground">Ohne Namen gespeichert – auch die Redaktion sieht nicht, wer wie abgestimmt hat.</span></span>
|
||||
<Switch v-model="form.anonymous" :disabled="hasVotes" />
|
||||
</label>
|
||||
<p v-if="form.errors.anonymous" class="text-[13px] text-destructive">{{ form.errors.anonymous }}</p>
|
||||
<p class="text-xs text-muted-foreground">Freitext-Antworten sieht nur die Redaktion.</p>
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<Panel title="Wer darf teilnehmen?">
|
||||
<p class="-mt-1 mb-3 flex items-start gap-2 text-[13px] text-muted-foreground">
|
||||
<Users class="mt-0.5 size-4 shrink-0" />
|
||||
{{ restricted ? 'Nur Personen, die mindestens eine Angabe erfüllen.' : 'Alle – oder unten eingrenzen.' }}
|
||||
</p>
|
||||
<AudienceEditor v-model="form.audience" :options="audienceOptions" exclude-hint="Sehen die Umfrage nie – auch wenn oben etwas passt." />
|
||||
</Panel>
|
||||
</div>
|
||||
</form>
|
||||
</AppLayout>
|
||||
</template>
|
||||
66
plugins-core/umfragen/resources/js/pages/Index.vue
Normal file
66
plugins-core/umfragen/resources/js/pages/Index.vue
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
<script setup>
|
||||
import { watch } from 'vue';
|
||||
import { Link, usePage } from '@inertiajs/vue3';
|
||||
import { CircleCheck, Plus, Vote } from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import EmptyState from '@/components/EmptyState.vue';
|
||||
import PageHeader from '@/components/PageHeader.vue';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import { formatShortDate } from '@/lib/format';
|
||||
|
||||
defineProps({
|
||||
open: { type: Array, required: true },
|
||||
closed: { type: Array, required: true },
|
||||
canManage: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const page = usePage();
|
||||
watch(() => page.props.flash.status, (status) => status && toast.success(status), { immediate: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout title="Umfragen">
|
||||
<PageHeader title="Umfragen" description="Ihre Meinung ist gefragt – Abstimmungen und Umfragen im Haus.">
|
||||
<template v-if="canManage" #actions>
|
||||
<Button as-child><Link href="/redaktion/umfragen/neu"><Plus /> Neue Umfrage</Link></Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-3">
|
||||
<Panel title="Laufende Umfragen" class="lg:col-span-2">
|
||||
<ul v-if="open.length" class="-mx-5 -mb-5 divide-y border-t">
|
||||
<li v-for="poll in open" :key="poll.id">
|
||||
<Link :href="poll.url" class="flex items-center gap-4 px-5 py-4 hover:bg-accent/40">
|
||||
<span class="grid size-10 shrink-0 place-items-center rounded-md" :class="poll.voted ? 'bg-muted text-muted-foreground' : 'bg-brand-soft text-brand-text'">
|
||||
<CircleCheck v-if="poll.voted" class="size-5" /><Vote v-else class="size-5" />
|
||||
</span>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block font-medium">{{ poll.title }}</span>
|
||||
<span class="block text-xs text-muted-foreground">
|
||||
{{ poll.questions_count }} {{ poll.questions_count === 1 ? 'Frage' : 'Fragen' }}<template v-if="poll.closes_at"> · bis {{ formatShortDate(poll.closes_at) }}</template>
|
||||
</span>
|
||||
</span>
|
||||
<span v-if="poll.voted" class="shrink-0 text-xs text-muted-foreground">Teilgenommen</span>
|
||||
<span v-else class="shrink-0 rounded-md bg-brand px-2.5 py-1 text-xs font-medium text-brand-foreground">Mitmachen</span>
|
||||
</Link>
|
||||
</li>
|
||||
</ul>
|
||||
<EmptyState v-else :icon="Vote" title="Gerade läuft keine Umfrage" class="py-8" />
|
||||
</Panel>
|
||||
|
||||
<Panel title="Beendet" class="content-start">
|
||||
<ul v-if="closed.length" class="-mx-5 -mb-5 divide-y border-t">
|
||||
<li v-for="poll in closed" :key="poll.id">
|
||||
<Link :href="poll.url" class="block px-5 py-3 hover:bg-accent/40">
|
||||
<span class="block text-sm font-medium">{{ poll.title }}</span>
|
||||
<span class="block text-xs text-muted-foreground">beendet am {{ formatShortDate(poll.closes_at) }}</span>
|
||||
</Link>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="text-sm text-muted-foreground">Noch keine beendeten Umfragen.</p>
|
||||
</Panel>
|
||||
</div>
|
||||
</AppLayout>
|
||||
</template>
|
||||
43
plugins-core/umfragen/resources/js/pages/Show.vue
Normal file
43
plugins-core/umfragen/resources/js/pages/Show.vue
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
<script setup>
|
||||
import { watch } from 'vue';
|
||||
import { Link, usePage } from '@inertiajs/vue3';
|
||||
import { Download, PencilLine } from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import PageHeader from '@/components/PageHeader.vue';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import { formatDate, formatTime } from '@/lib/format';
|
||||
import PollForm from '../components/PollForm.vue';
|
||||
|
||||
defineProps({
|
||||
poll: { type: Object, required: true },
|
||||
});
|
||||
|
||||
const page = usePage();
|
||||
watch(() => page.props.flash.status, (status) => status && toast.success(status), { immediate: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout :title="poll.title">
|
||||
<div class="mx-auto max-w-3xl">
|
||||
<PageHeader :title="poll.title" :breadcrumbs="[{ label: 'Umfragen', href: '/umfragen' }]">
|
||||
<template #description>
|
||||
<template v-if="poll.status === 'draft'">Entwurf – nur für die Redaktion sichtbar.</template>
|
||||
<template v-else-if="poll.open && poll.closes_at">Läuft bis {{ formatDate(poll.closes_at) }}, {{ formatTime(poll.closes_at) }} Uhr</template>
|
||||
<template v-else-if="poll.open">Läuft</template>
|
||||
<template v-else-if="poll.closes_at">Beendet am {{ formatDate(poll.closes_at) }}</template>
|
||||
</template>
|
||||
<template v-if="poll.edit_url" #actions>
|
||||
<Button variant="outline" size="sm" as-child><a :href="poll.export_url"><Download /> Ergebnisse (CSV)</a></Button>
|
||||
<Button variant="outline" size="sm" as-child><Link :href="poll.edit_url"><PencilLine /> Bearbeiten</Link></Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<Panel>
|
||||
<p v-if="poll.description" class="mb-6 text-[15px] leading-relaxed whitespace-pre-line">{{ poll.description }}</p>
|
||||
<PollForm :poll="poll" />
|
||||
</Panel>
|
||||
</div>
|
||||
</AppLayout>
|
||||
</template>
|
||||
26
plugins-core/umfragen/resources/js/widgets/Open.vue
Normal file
26
plugins-core/umfragen/resources/js/widgets/Open.vue
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { Vote } from '@lucide/vue';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import { formatShortDate } from '@/lib/format';
|
||||
|
||||
defineProps({
|
||||
polls: { type: Array, required: true },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Panel title="Ihre Meinung ist gefragt" action-label="Alle Umfragen" action-href="/umfragen">
|
||||
<ul class="-my-1 grid gap-1">
|
||||
<li v-for="poll in polls" :key="poll.id">
|
||||
<Link :href="poll.url" class="group -mx-2 flex items-center gap-3 rounded-md p-2 hover:bg-accent/50">
|
||||
<span class="grid size-9 shrink-0 place-items-center rounded-md bg-brand-soft text-brand-text"><Vote class="size-4.5" /></span>
|
||||
<span class="min-w-0">
|
||||
<span class="line-clamp-2 text-sm leading-snug font-medium group-hover:underline">{{ poll.title }}</span>
|
||||
<span v-if="poll.closes_at" class="block text-xs text-muted-foreground">bis {{ formatShortDate(poll.closes_at) }}</span>
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</Panel>
|
||||
</template>
|
||||
9
plugins-core/umfragen/routes/api.php
Normal file
9
plugins-core/umfragen/routes/api.php
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Inhaus\Plugins\Umfragen\Http\Controllers\PollController;
|
||||
|
||||
// /api/v1/polls … (Token nötig, siehe docs/API.md)
|
||||
Route::get('/polls', [PollController::class, 'apiIndex']);
|
||||
Route::get('/polls/{poll}', [PollController::class, 'apiShow'])->whereNumber('poll');
|
||||
Route::post('/polls/{poll}/vote', [PollController::class, 'vote'])->whereNumber('poll')->middleware('throttle:30,1');
|
||||
21
plugins-core/umfragen/routes/web.php
Normal file
21
plugins-core/umfragen/routes/web.php
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Inhaus\Plugins\Umfragen\Http\Controllers\PollController;
|
||||
use Inhaus\Plugins\Umfragen\Http\Controllers\PollEditorController;
|
||||
|
||||
Route::middleware('auth')->group(function () {
|
||||
Route::get('/umfragen', [PollController::class, 'index'])->name('polls.index');
|
||||
|
||||
Route::prefix('redaktion/umfragen')->name('polls.')->controller(PollEditorController::class)->group(function () {
|
||||
Route::get('/neu', 'create')->name('create');
|
||||
Route::post('/', 'store')->name('store');
|
||||
Route::get('/{poll}', 'edit')->name('edit');
|
||||
Route::put('/{poll}', 'update')->name('update');
|
||||
Route::delete('/{poll}', 'destroy')->name('destroy');
|
||||
Route::get('/{poll}/ergebnisse.csv', 'export')->name('export');
|
||||
});
|
||||
|
||||
Route::get('/umfragen/{poll}', [PollController::class, 'show'])->name('polls.show');
|
||||
Route::post('/umfragen/{poll}/abstimmen', [PollController::class, 'vote'])->middleware('throttle:30,1')->name('polls.vote');
|
||||
});
|
||||
38
plugins-core/umfragen/src/Announcer.php
Normal file
38
plugins-core/umfragen/src/Announcer.php
Normal 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));
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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']))];
|
||||
}
|
||||
}
|
||||
127
plugins-core/umfragen/src/Models/Poll.php
Normal file
127
plugins-core/umfragen/src/Models/Poll.php
Normal 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();
|
||||
}
|
||||
}
|
||||
27
plugins-core/umfragen/src/Models/PollResponse.php
Normal file
27
plugins-core/umfragen/src/Models/PollResponse.php
Normal 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);
|
||||
}
|
||||
}
|
||||
60
plugins-core/umfragen/src/Presenter.php
Normal file
60
plugins-core/umfragen/src/Presenter.php
Normal 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),
|
||||
];
|
||||
}
|
||||
}
|
||||
135
plugins-core/umfragen/src/Questions.php
Normal file
135
plugins-core/umfragen/src/Questions.php
Normal 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));
|
||||
}
|
||||
}
|
||||
55
plugins-core/umfragen/src/Results.php
Normal file
55
plugins-core/umfragen/src/Results.php
Normal 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(),
|
||||
];
|
||||
}
|
||||
}
|
||||
57
plugins-core/umfragen/src/UmfragenPlugin.php
Normal file
57
plugins-core/umfragen/src/UmfragenPlugin.php
Normal 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);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue