feat: let teamers fill in and read their questionnaire
This commit is contained in:
1 parent
2a041d25a0
commit
5e4e574076
11 files changed
+472
-2
No files matched your search
@@ -0,0 +1,74 @@
|
||||
import { Controller } from '@hotwired/stimulus'
|
||||
|
||||
/*
|
||||
* Shows a questionnaire question only while its show_if holds, mirroring
|
||||
* App\Model\Questionnaire\Definition::isVisible(): the condition must be met and the question it
|
||||
* depends on must itself be shown.
|
||||
*
|
||||
* Every question row carries data-question-key; a conditional one also data-show-if, the JSON
|
||||
* {question, operator, value} that App\Form\QuestionnaireType writes. A hidden row stays in the
|
||||
* form and is submitted: a draft keeps its answer, and the server drops it on submit.
|
||||
*/
|
||||
export default class extends Controller {
|
||||
|
||||
connect() {
|
||||
this.update()
|
||||
}
|
||||
|
||||
update() {
|
||||
const visible = {}
|
||||
|
||||
// Rows come in definition order, and a condition may only name an earlier question, so
|
||||
// the question a row depends on has always been decided by the time the row is reached.
|
||||
for (const row of this.element.querySelectorAll('[data-question-key]')) {
|
||||
const key = row.dataset.questionKey
|
||||
const condition = row.dataset.showIf ? JSON.parse(row.dataset.showIf) : null
|
||||
|
||||
visible[key] = null === condition
|
||||
|| (true === visible[condition.question] && this.isMet(condition))
|
||||
|
||||
row.hidden = false === visible[key]
|
||||
}
|
||||
}
|
||||
|
||||
isMet({ question, operator, value }) {
|
||||
const answer = this.answer(question)
|
||||
|
||||
if (null === answer) {
|
||||
return false
|
||||
}
|
||||
|
||||
switch (operator) {
|
||||
case 'equals':
|
||||
return answer === value
|
||||
case 'in':
|
||||
return value.includes(answer)
|
||||
case 'lte':
|
||||
return Number(answer) <= value
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
answer(key) {
|
||||
const row = this.element.querySelector(`[data-question-key="${key}"]`)
|
||||
|
||||
if (null === row) {
|
||||
return null
|
||||
}
|
||||
|
||||
const checked = row.querySelector('input[type="radio"]:checked')
|
||||
|
||||
if (null !== checked) {
|
||||
return checked.value
|
||||
}
|
||||
|
||||
const select = row.querySelector('select')
|
||||
|
||||
if (null !== select) {
|
||||
return '' === select.value ? null : select.value
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,11 @@ use Symfony\Component\Yaml\Yaml;
|
||||
*/
|
||||
class QuestionnaireCatalog
|
||||
{
|
||||
/**
|
||||
* The questionnaire a teamer fills in after a bus escort; see DispositionVoter::QUESTIONNAIRE.
|
||||
*/
|
||||
public const string TEAMER_ESCORT = 'teamer_escort';
|
||||
|
||||
private const array ROOT_FIELDS = ['key', 'version', 'title', 'description', 'sections'];
|
||||
private const array SECTION_FIELDS = ['key', 'title', 'questions'];
|
||||
private const array QUESTION_FIELDS = ['key', 'label', 'type', 'required', 'help', 'widget', 'options', 'show_if'];
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller\Teamer\Questionnaire;
|
||||
|
||||
use App\Config\QuestionnaireCatalog;
|
||||
use App\Entity\Disposition;
|
||||
use App\Repository\QuestionnaireResponseRepository;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
|
||||
/**
|
||||
* The teamer's own submitted questionnaire, read-only, rendered with the definition version it
|
||||
* was submitted under.
|
||||
*/
|
||||
class DetailController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly QuestionnaireCatalog $catalog,
|
||||
private readonly QuestionnaireResponseRepository $responseRepository,
|
||||
) {
|
||||
}
|
||||
|
||||
#[Route('/teamer/questionnaire/{uuid}/detail', name: 'app_teamer_questionnaire_detail')]
|
||||
#[IsGranted('ROLE_TEAMER')]
|
||||
#[IsGranted('QUESTIONNAIRE', subject: 'disposition')]
|
||||
public function index(Disposition $disposition): Response
|
||||
{
|
||||
$response = $this->responseRepository->findOneByDisposition(QuestionnaireCatalog::TEAMER_ESCORT, $disposition);
|
||||
|
||||
if (true !== $response?->isSubmitted()) {
|
||||
return $this->redirectToRoute('app_teamer_questionnaire_edit', ['uuid' => $disposition->getUuid()]);
|
||||
}
|
||||
|
||||
return $this->render('teamer/questionnaire/detail.html.twig', [
|
||||
'disposition' => $disposition,
|
||||
'definition' => $this->catalog->get($response->getQuestionnaire(), $response->getVersion()),
|
||||
'response' => $response,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller\Teamer\Questionnaire;
|
||||
|
||||
use App\Config\QuestionnaireCatalog;
|
||||
use App\Entity\Disposition;
|
||||
use App\Entity\QuestionnaireResponse;
|
||||
use App\Form\QuestionnaireType;
|
||||
use App\Repository\QuestionnaireResponseRepository;
|
||||
use App\Service\Questionnaire\DispositionContext;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
|
||||
/**
|
||||
* The teamer's questionnaire after a bus escort, saved as a draft until it is submitted. A
|
||||
* submitted one is final and only shown read-only (DetailController).
|
||||
*/
|
||||
class EditController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly QuestionnaireCatalog $catalog,
|
||||
private readonly QuestionnaireResponseRepository $responseRepository,
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
#[Route('/teamer/questionnaire/{uuid}', name: 'app_teamer_questionnaire_edit')]
|
||||
#[IsGranted('ROLE_TEAMER')]
|
||||
#[IsGranted('QUESTIONNAIRE', subject: 'disposition')]
|
||||
public function index(Disposition $disposition, Request $request): Response
|
||||
{
|
||||
$response = $this->responseRepository->findOneByDisposition(QuestionnaireCatalog::TEAMER_ESCORT, $disposition);
|
||||
|
||||
if (true === $response?->isSubmitted()) {
|
||||
return $this->redirectToRoute('app_teamer_questionnaire_detail', ['uuid' => $disposition->getUuid()]);
|
||||
}
|
||||
|
||||
$definition = $this->catalog->get(QuestionnaireCatalog::TEAMER_ESCORT);
|
||||
|
||||
$form = $this->createForm(QuestionnaireType::class, $response?->getAnswers() ?? [], [
|
||||
'definition' => $definition,
|
||||
]);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
if (null === $response) {
|
||||
$response = QuestionnaireResponse::forDisposition($definition, $disposition);
|
||||
$this->entityManager->persist($response);
|
||||
}
|
||||
|
||||
$context = DispositionContext::build($disposition);
|
||||
$final = QuestionnaireType::isFinal($form);
|
||||
|
||||
if (true === $final) {
|
||||
$response->submit($definition, $form->getData(), $context, new \DateTimeImmutable());
|
||||
} else {
|
||||
$response->saveDraft($form->getData(), $context);
|
||||
}
|
||||
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->logger->info($final ? 'Submit questionnaire' : 'Save questionnaire draft', [
|
||||
'questionnaire' => $response->getQuestionnaire(),
|
||||
'questionnaire_response_id' => $response->getId(),
|
||||
'disposition_id' => $disposition->getId(),
|
||||
'teamer_id' => $disposition->getTeamer()->getId(),
|
||||
]);
|
||||
|
||||
if (true === $final) {
|
||||
$this->addFlash('success', 'Danke! Dein Fragebogen wurde abgeschickt.');
|
||||
|
||||
return $this->redirectToRoute('app_teamer_questionnaire_detail', ['uuid' => $disposition->getUuid()]);
|
||||
}
|
||||
|
||||
$this->addFlash('success', 'Dein Entwurf wurde gespeichert.');
|
||||
|
||||
return $this->redirectToRoute('app_teamer_questionnaire_edit', ['uuid' => $disposition->getUuid()]);
|
||||
}
|
||||
|
||||
return $this->render('teamer/questionnaire/edit.html.twig', [
|
||||
'disposition' => $disposition,
|
||||
'definition' => $definition,
|
||||
'response' => $response,
|
||||
'form' => $form,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -120,13 +120,14 @@ class QuestionnaireType extends AbstractType
|
||||
'label' => $question->label,
|
||||
'help' => $question->help,
|
||||
'required' => false,
|
||||
'row_attr' => null === $question->showIf ? [] : [
|
||||
// read by assets/controllers/questionnaire_controller.js
|
||||
'row_attr' => ['data-question-key' => $question->key] + (null === $question->showIf ? [] : [
|
||||
'data-show-if' => json_encode([
|
||||
'question' => $question->showIf->question,
|
||||
'operator' => $question->showIf->operator->value,
|
||||
'value' => $question->showIf->value,
|
||||
], JSON_THROW_ON_ERROR),
|
||||
],
|
||||
]),
|
||||
];
|
||||
|
||||
return match ($question->type) {
|
||||
|
||||
@@ -134,6 +134,12 @@ class TeamerMenuBuilder extends AbstractMenuBuilder
|
||||
'linkAttributes' => [
|
||||
'title' => 'Letzte Einsätze',
|
||||
],
|
||||
// the questionnaire after a past bus escort
|
||||
'extras' => [
|
||||
'routes' => [
|
||||
['pattern' => '/^app_teamer_questionnaire_/'],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$menu->addChild('Dokumente', [
|
||||
|
||||
@@ -173,6 +173,38 @@
|
||||
{%- endif -%}
|
||||
{%- endblock pickup_choice_widget -%}
|
||||
|
||||
{#
|
||||
# A section of a questionnaire (App\Form\QuestionnaireType): its title and its questions. The
|
||||
# questions' rows carry data-question-key and, when conditional, data-show-if, which
|
||||
# assets/controllers/questionnaire_controller.js reads to show and hide them.
|
||||
#}
|
||||
{%- block questionnaire_section_row -%}
|
||||
<fieldset class="pb-8">
|
||||
{%- if label is not same as(false) -%}
|
||||
<legend class="text-xl font-bold pb-4">{{ label }}</legend>
|
||||
{%- endif -%}
|
||||
<div class="flex flex-col gap-y-6">
|
||||
{%- for child in form -%}
|
||||
{{- form_row(child) -}}
|
||||
{%- endfor -%}
|
||||
</div>
|
||||
</fieldset>
|
||||
{%- endblock questionnaire_section_row -%}
|
||||
|
||||
{# A 1-5 rating as a row of buttons, the radios themselves hidden. #}
|
||||
{%- block questionnaire_rating_widget -%}
|
||||
<div class="flex gap-x-2" role="radiogroup">
|
||||
{%- for child in form -%}
|
||||
<label class="cursor-pointer">
|
||||
{{- form_widget(child, { attr: { class: 'peer sr-only' } }) -}}
|
||||
<span class="{{ html_classes('flex h-10 w-10 items-center justify-center rounded-md text-sm font-bold ring-1 ring-inset peer-checked:bg-primary peer-checked:text-white peer-checked:ring-primary peer-focus-visible:ring-2', { 'ring-red-500 text-red-500': errors|length, 'ring-gray-300 text-gray-900': not errors|length }) }}">
|
||||
{{- child.vars.label -}}
|
||||
</span>
|
||||
</label>
|
||||
{%- endfor -%}
|
||||
</div>
|
||||
{%- endblock questionnaire_rating_widget -%}
|
||||
|
||||
{%- block birthday_widget -%}
|
||||
<div class="grid grid-cols-3 gap-x-1">
|
||||
{{ form_widget(form.children['day']) }}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
{#
|
||||
# A submitted questionnaire response, read-only. Expects `definition` (the version the response
|
||||
# was submitted under) and `response`. Questions that are hidden or were left open are skipped;
|
||||
# an answer the definition does not know (an option key since renamed) is shown as stored rather
|
||||
# than dropped.
|
||||
#}
|
||||
{% set answers = response.answers %}
|
||||
<div class="flex flex-col gap-y-8">
|
||||
{% for section in definition.sections %}
|
||||
{% set shown = section.questions|filter(question => answers[question.key] is defined and definition.isVisible(question, answers)) %}
|
||||
{% if shown is not empty %}
|
||||
<section>
|
||||
{% if section.title %}
|
||||
<h2 class="text-lg font-bold pb-2">
|
||||
{{ section.title }}
|
||||
</h2>
|
||||
{% endif %}
|
||||
<dl class="divide-y divide-gray-100">
|
||||
{% for question in shown %}
|
||||
{% set answer = answers[question.key] %}
|
||||
<div class="py-4 sm:grid sm:grid-cols-2 sm:gap-4">
|
||||
<dt class="text-sm font-bold leading-6 text-gray-900">
|
||||
{{ question.label|nl2br }}
|
||||
</dt>
|
||||
<dd class="mt-1 text-sm leading-6 text-gray-700 sm:mt-0">
|
||||
{% if question.type.value == 'rating' %}
|
||||
<span class="inline-flex items-center gap-x-2">
|
||||
<span class="inline-flex items-center">
|
||||
{% for grade in range(1, 5) %}
|
||||
{{ icon('star', html_classes('w-4 h-4', { 'text-gray-200': answer < grade, 'text-primary': answer >= grade })) }}
|
||||
{% endfor %}
|
||||
</span>
|
||||
{{ answer }} von 5
|
||||
</span>
|
||||
{% elseif question.type.value == 'choice' %}
|
||||
{{ (question.option(answer).label ?? answer) }}
|
||||
{% elseif question.type.value == 'multi' %}
|
||||
{{ answer|map(key => (question.option(key).label ?? key))|join(', ') }}
|
||||
{% elseif question.type.value == 'date' %}
|
||||
{{ answer|date('d.m.Y') }}
|
||||
{% else %}
|
||||
{{ answer|nl2br }}
|
||||
{% endif %}
|
||||
</dd>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</dl>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
@@ -0,0 +1,23 @@
|
||||
{% extends 'teamer/layout.html.twig' %}
|
||||
|
||||
{% block title %}{{ definition.title }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1 class="text-2xl font-bold pb-4">
|
||||
{{ definition.title }}
|
||||
</h1>
|
||||
<p class="pb-8 text-gray-700">
|
||||
Abgeschickt am {{ response.submittedAt|date('d.m.Y, H:i') }} Uhr. Danke für dein Feedback!
|
||||
</p>
|
||||
<div class="grid lg:grid-cols-3 gap-8 items-start">
|
||||
<div class="lg:col-span-2">
|
||||
{% include 'questionnaire/_answers.html.twig' %}
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-lg font-bold pb-4">
|
||||
Dein Einsatz
|
||||
</h2>
|
||||
{% include '_partials/_assignment_info.html.twig' with { 'assignment': disposition.assignment } %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,42 @@
|
||||
{% extends 'teamer/layout.html.twig' %}
|
||||
|
||||
{% block title %}{{ definition.title }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1 class="text-2xl font-bold pb-4">
|
||||
{{ definition.title }}
|
||||
</h1>
|
||||
{% if definition.description %}
|
||||
<p class="pb-8 text-gray-700">
|
||||
{{ definition.description|nl2br }}
|
||||
</p>
|
||||
{% endif %}
|
||||
<div class="grid lg:grid-cols-3 gap-8 items-start">
|
||||
<div class="lg:col-span-2">
|
||||
{{ form_start(form, { attr: { 'data-controller': 'questionnaire', 'data-action': 'change->questionnaire#update' } }) }}
|
||||
{% for child in form|filter(child => child.vars.name not in ['draft', 'submit']) %}
|
||||
{{ form_row(child) }}
|
||||
{% endfor %}
|
||||
<div class="flex flex-wrap items-center gap-4 pt-4">
|
||||
{{ form_widget(form.submit, { attr: { class: 'btn' } }) }}
|
||||
{{ form_widget(form.draft, { attr: { class: 'btn btn--secondary' } }) }}
|
||||
</div>
|
||||
<p class="pt-2 text-sm text-gray-500">
|
||||
Als Entwurf kannst du den Fragebogen jederzeit speichern und später weiter ausfüllen.
|
||||
Abgeschickt ist er endgültig.
|
||||
</p>
|
||||
{{ form_end(form) }}
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-lg font-bold pb-4">
|
||||
Dein Einsatz
|
||||
</h2>
|
||||
{% include '_partials/_assignment_info.html.twig' with { 'assignment': disposition.assignment } %}
|
||||
{% if response %}
|
||||
<p class="pt-6 text-sm text-gray-500">
|
||||
Entwurf zuletzt gespeichert am {{ (response.updatedAt ?? response.createdAt)|date('d.m.Y, H:i') }} Uhr
|
||||
</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Twig;
|
||||
|
||||
use App\Config\QuestionnaireCatalog;
|
||||
use App\Entity\Application;
|
||||
use App\Entity\Assignment;
|
||||
use App\Entity\Disposition;
|
||||
use App\Entity\QuestionnaireResponse;
|
||||
use App\Entity\Teamer;
|
||||
use App\Form\QuestionnaireType;
|
||||
use App\Model\Questionnaire\Definition;
|
||||
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
|
||||
use Symfony\Component\DomCrawler\Crawler;
|
||||
use Symfony\Component\Form\FormFactoryInterface;
|
||||
use Twig\Environment;
|
||||
|
||||
/**
|
||||
* The questionnaire's form-theme blocks and the read-only answers partial, rendered for real:
|
||||
* a misspelt block prefix silently falls back to Symfony's default markup, which would drop the
|
||||
* data attributes the show/hide controller needs.
|
||||
*/
|
||||
class QuestionnaireTemplateTest extends KernelTestCase
|
||||
{
|
||||
public function testEveryQuestionRowCarriesItsKeyAndConditionalOnesTheirCondition(): void
|
||||
{
|
||||
$crawler = $this->renderForm();
|
||||
|
||||
$this->assertCount(count($this->definition()->getQuestions()), $crawler->filter('[data-question-key]'));
|
||||
$this->assertSame(
|
||||
'{"question":"bus_company","operator":"equals","value":"other"}',
|
||||
$crawler->filter('[data-question-key="bus_company_other"]')->attr('data-show-if'),
|
||||
);
|
||||
}
|
||||
|
||||
public function testSectionsAreFieldsetsWithTheirTitle(): void
|
||||
{
|
||||
$crawler = $this->renderForm();
|
||||
|
||||
$this->assertSame('Organisation & Ablauf', trim($crawler->filter('fieldset legend')->first()->text()));
|
||||
$this->assertCount(count($this->definition()->sections), $crawler->filter('fieldset'));
|
||||
}
|
||||
|
||||
public function testRatingIsFiveRadiosInARadioGroup(): void
|
||||
{
|
||||
$group = $this->renderForm()->filter('[data-question-key="office_briefing_rating"] [role="radiogroup"]');
|
||||
|
||||
$this->assertCount(5, $group->filter('input[type="radio"]'));
|
||||
}
|
||||
|
||||
public function testAnswersShowLabelsNotKeysAndSkipHiddenQuestions(): void
|
||||
{
|
||||
$definition = $this->definition();
|
||||
$response = QuestionnaireResponse::forDisposition($definition, new Disposition(new Application(new Assignment(), new Teamer())))
|
||||
->submit($definition, [
|
||||
'office_briefing_rating' => 2,
|
||||
'office_briefing_low_reason' => 'Briefing kam zu spät',
|
||||
'bus_company' => 'heess',
|
||||
'had_organisational_problems' => 'no',
|
||||
], [], new \DateTimeImmutable())
|
||||
;
|
||||
|
||||
$html = self::getContainer()->get(Environment::class)->render('questionnaire/_answers.html.twig', [
|
||||
'definition' => $definition,
|
||||
'response' => $response,
|
||||
]);
|
||||
|
||||
$this->assertStringContainsString('2 von 5', $html);
|
||||
$this->assertStringContainsString('Briefing kam zu spät', $html);
|
||||
$this->assertStringContainsString('Heeß', $html);
|
||||
$this->assertStringContainsString('Nein', $html);
|
||||
$this->assertStringNotContainsString('heess', $html);
|
||||
// nothing was answered there, so the section is left out
|
||||
$this->assertStringNotContainsString('Bewertung Bus & Fahrer', $html);
|
||||
}
|
||||
|
||||
private function renderForm(): Crawler
|
||||
{
|
||||
self::bootKernel();
|
||||
$container = self::getContainer();
|
||||
|
||||
$form = $container->get(FormFactoryInterface::class)->create(QuestionnaireType::class, [], [
|
||||
'definition' => $this->definition(),
|
||||
'csrf_protection' => false,
|
||||
]);
|
||||
|
||||
$html = $container->get(Environment::class)
|
||||
->createTemplate('{{ form(form) }}')
|
||||
->render(['form' => $form->createView()])
|
||||
;
|
||||
|
||||
return new Crawler($html);
|
||||
}
|
||||
|
||||
private function definition(): Definition
|
||||
{
|
||||
return new QuestionnaireCatalog(__DIR__.'/../../config/questionnaires')->get(QuestionnaireCatalog::TEAMER_ESCORT);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user