Loheide-eu-mitarbeiterplatt.../tests/Feature/Forms/FormsTest.php
Friederich Loheide ee8dde93c0
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m18s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m21s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m40s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m34s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 3m8s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 3m6s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 2m43s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 2m47s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m1s
Feste Profilfelder in Formularen, Geburtstage, anpassbare Startseite
- Formulare: Felder fest aus dem Profil (nicht änderbar, Server setzt den
  Profilwert ein), Hinweis bei fehlender Profilangabe
- Geburtstage (optionales Plugin, standardmäßig aus): Tag und Monat freiwillig
  im Profil, Kachel, Liste /geburtstage, Pagebuilder-Block, Glückwunsch am
  eigenen Geburtstag; Sichtbarkeit alle/Abteilung/Standort
- Startseite: Kacheln je Bereich sortieren und ausblenden; eigene Kacheln
  (Bild mit Link, Text, Hinweis) mit Zeitraum und Zielgruppe
- Kern: optionale mitgelieferte Plugins, Startseitenbereich „top“,
  Profilabschnitte für Plugins, Kachel-Bezeichnungen

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 09:51:19 +00:00

391 lines
22 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Tests\Feature\Forms;
use App\Models\ProfileField;
use App\Models\Role;
use App\Models\User;
use App\Notifications\PortalNotification;
use App\Pagebuilder\Content;
use App\Support\Permissions\Audiences;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Inertia\Testing\AssertableInertia as Assert;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\CreateForm;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\FormResults;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\ListForms;
use Inhaus\Plugins\Forms\Mail\FormSubmitted;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Models\FormSubmission;
use Inhaus\Plugins\Forms\Retention;
use Livewire\Livewire;
use Tests\TestCase;
class FormsTest extends TestCase
{
use RefreshDatabase;
private User $employee;
protected function setUp(): void
{
parent::setUp();
Storage::fake('local');
Mail::fake();
Notification::fake();
$this->employee = User::factory()->create(['first_name' => 'Anna', 'last_name' => 'Schmidt', 'email' => 'anna@firma.de', 'department' => 'Pflege']);
}
private function trainingForm(array $settings = [], array $attributes = []): Form
{
return Form::query()->create([
'title' => 'Antrag auf Fortbildung',
'fields' => [
['type' => 'heading', 'data' => ['text' => 'Angaben zur Person']],
['type' => 'text', 'data' => ['label' => 'Name', 'required' => true, 'prefill' => 'name']],
['type' => 'select', 'data' => ['label' => 'Art', 'required' => true, 'options' => ['Seminar', 'Studium', 'Sonstiges']]],
['type' => 'textarea', 'data' => ['label' => 'Welche?', 'required' => true, 'condition_field' => 'art', 'condition_operator' => 'equals', 'condition_value' => 'Sonstiges']],
['type' => 'number', 'data' => ['label' => 'Kosten', 'min' => 0, 'max' => 5000]],
['type' => 'checkboxes', 'data' => ['label' => 'Tage', 'options' => ['Mo', 'Di', 'Mi']]],
['type' => 'file', 'data' => ['label' => 'Nachweis', 'accept' => 'documents', 'max_size' => 2]],
['type' => 'checkbox', 'data' => ['label' => 'Ich stimme der Verarbeitung zu', 'key' => 'zustimmung', 'required' => true]],
],
'settings' => array_merge(['notify_emails' => ['personal@firma.de']], $settings),
...$attributes,
]);
}
private function resultsRole(Form $form, bool $delete = false): Role
{
$role = Role::query()->create(['name' => 'Personalabteilung']);
$role->grants()->create(['ability' => 'forms.results', 'resource_type' => 'form', 'resource_id' => $form->id]);
if ($delete) {
$role->grants()->create(['ability' => 'forms.results.delete', 'resource_type' => 'form', 'resource_id' => $form->id]);
}
return $role;
}
public function test_keys_are_generated_and_unique(): void
{
$form = Form::query()->create(['title' => 'Test', 'fields' => [
['type' => 'text', 'data' => ['label' => 'Straße & Nr.']],
['type' => 'text', 'data' => ['label' => 'Straße & Nr.']],
['type' => 'unbekannt', 'data' => ['label' => 'x']],
]]);
$this->assertSame(['strasse_nr', 'strasse_nr_2'], array_column(array_column($form->fields, 'data'), 'key'));
$this->assertSame('test', $form->slug);
}
public function test_employee_fills_in_the_form_and_hr_is_notified(): void
{
$form = $this->trainingForm(['notify_viewers' => true, 'send_copy' => true]);
$hr = User::factory()->withRoles([$this->resultsRole($form)])->create();
$this->actingAs($this->employee)->get('/formulare/antrag-auf-fortbildung')->assertOk()->assertInertia(fn (Assert $p) => $p
->component('forms::Show')
->where('form.prefill.name', 'Anna Schmidt')
->where('form.fields.3.condition', ['field' => 'art', 'operator' => 'equals', 'value' => 'Sonstiges']));
// Pflichtfelder, Auswahl nur aus den Optionen, Bedingung greift.
$this->post('/formulare/antrag-auf-fortbildung', ['answers' => ['name' => 'Anna Schmidt', 'art' => 'Sonstiges', 'kosten' => 9999]])
->assertSessionHasErrors(['answers.welche', 'answers.kosten', 'answers.zustimmung']);
$this->post('/formulare/antrag-auf-fortbildung', ['answers' => ['name' => 'Anna', 'art' => 'Erfunden', 'zustimmung' => '1']])
->assertSessionHasErrors(['answers.art']);
$this->from('/formulare/antrag-auf-fortbildung')->post('/formulare/antrag-auf-fortbildung', ['answers' => [
'name' => 'Anna Schmidt',
'art' => 'Seminar',
'welche' => 'wird ignoriert, weil ausgeblendet',
'kosten' => '450',
'tage' => ['Mo', 'Mi'],
'nachweis' => [UploadedFile::fake()->create('Angebot.pdf', 100, 'application/pdf')],
'zustimmung' => '1',
]])->assertRedirect('/formulare/antrag-auf-fortbildung')->assertSessionHas('form_submitted', $form->id);
$submission = FormSubmission::query()->sole();
$this->assertSame($this->employee->id, $submission->user_id);
$this->assertArrayNotHasKey('welche', $submission->data);
$this->assertSame('Mo, Mi', $submission->display('tage'));
$this->assertSame('Ja', $submission->display('zustimmung'));
$this->assertSame('Angebot.pdf', $submission->display('nachweis'));
Storage::disk('local')->assertExists($submission->files->sole()->path);
Mail::assertQueued(FormSubmitted::class, fn (FormSubmitted $m) => $m->hasTo('personal@firma.de') && ! $m->copy && $m->hasReplyTo('anna@firma.de'));
Mail::assertQueued(FormSubmitted::class, fn (FormSubmitted $m) => $m->hasTo($hr->email) && ! $m->copy);
Mail::assertQueued(FormSubmitted::class, fn (FormSubmitted $m) => $m->hasTo('anna@firma.de') && $m->copy);
Notification::assertSentTo($hr, PortalNotification::class);
$html = (new FormSubmitted($form, $submission, $this->employee, false))->render();
$this->assertStringContainsString('Anna Schmidt (anna@firma.de)', $html);
$this->assertStringContainsString('Mo, Mi', $html);
}
public function test_results_are_only_visible_to_roles_granted_for_this_form(): void
{
$training = $this->trainingForm();
$other = Form::query()->create(['title' => 'Meldung an die MAV', 'fields' => [['type' => 'text', 'data' => ['label' => 'Anliegen']]]]);
$training->submissions()->create(['user_id' => $this->employee->id, 'data' => ['name' => ['label' => 'Name', 'type' => 'text', 'value' => 'Anna Schmidt']]]);
$other->submissions()->create(['data' => ['anliegen' => ['label' => 'Anliegen', 'type' => 'text', 'value' => 'Vertraulich']]]);
$hr = User::factory()->withRoles([$this->resultsRole($training)])->create();
$this->actingAs($hr)->get('/admin/formulare')->assertOk();
Livewire::test(ListForms::class)->assertCanSeeTableRecords([$training])->assertCanNotSeeTableRecords([$other]);
$this->get('/admin/formulare/'.$training->id.'/ergebnisse')->assertOk()->assertSee('Anna Schmidt');
$this->get('/admin/formulare/'.$other->id.'/ergebnisse')->assertNotFound();
$this->get('/admin/formulare/'.$training->id.'/bearbeiten')->assertForbidden();
$this->get('/admin/formulare/'.$other->id.'/export')->assertForbidden();
$csv = $this->get('/admin/formulare/'.$training->id.'/export')->assertOk()->streamedContent();
$this->assertStringStartsWith("\xEF\xBB\xBF", $csv);
$this->assertStringContainsString('Anna Schmidt', $csv);
// Ohne Löschrecht kein Löschen; ansehen markiert als gelesen.
$submission = $training->submissions()->sole();
Livewire::test(FormResults::class, ['record' => $training->id])
->assertTableActionHidden('delete', $submission)
->callTableAction('view', $submission);
$this->assertNotNull($submission->fresh()->read_at);
$this->actingAs($this->employee)->get('/admin/formulare/'.$training->id.'/ergebnisse')->assertForbidden();
}
public function test_uploaded_files_are_only_served_to_result_viewers(): void
{
$form = $this->trainingForm();
$this->actingAs($this->employee)->post('/formulare/antrag-auf-fortbildung', ['answers' => [
'name' => 'Anna', 'art' => 'Seminar', 'zustimmung' => '1',
'nachweis' => [UploadedFile::fake()->create('Zeugnis.pdf', 50, 'application/pdf')],
]])->assertSessionHasNoErrors();
$file = FormSubmission::query()->sole()->files->sole();
$this->get($file->url())->assertForbidden();
$this->actingAs(User::factory()->withRoles([$this->resultsRole($form)])->create())->get($file->url())->assertOk()->assertDownload('Zeugnis.pdf');
$this->actingAs($this->employee)->post('/formulare/antrag-auf-fortbildung', ['answers' => [
'name' => 'Anna', 'art' => 'Seminar', 'zustimmung' => '1',
'nachweis' => [UploadedFile::fake()->create('virus.php', 1)],
]])->assertSessionHasErrors('answers.nachweis.0');
}
public function test_anonymous_forms_store_no_identity_but_allow_only_one_submission(): void
{
$form = Form::query()->create([
'title' => 'Mitarbeiterbefragung',
'fields' => [['type' => 'radio', 'data' => ['label' => 'Zufriedenheit', 'required' => true, 'options' => ['gut', 'mittel', 'schlecht']]]],
'settings' => ['anonymous' => true, 'once_per_user' => true, 'notify_emails' => ['mav@firma.de']],
]);
$this->actingAs($this->employee)->post($form->url(), ['answers' => ['zufriedenheit' => 'gut']])->assertSessionHasNoErrors();
$this->post($form->url(), ['answers' => ['zufriedenheit' => 'schlecht']])->assertSessionHasErrors('form');
$submission = FormSubmission::query()->sole();
$this->assertNull($submission->user_id);
$this->assertNotNull($submission->user_hash);
Mail::assertQueued(FormSubmitted::class, fn (FormSubmitted $m) => $m->person === null);
$this->get($form->url())->assertInertia(fn (Assert $p) => $p->where('form.already_submitted', true)->where('form.anonymous', true));
}
public function test_audience_and_deadline_limit_who_can_submit(): void
{
$form = $this->trainingForm(attributes: ['closes_at' => now()->addDay()]);
Audiences::sync('form', $form->id, ['department' => ['Verwaltung']]);
$this->actingAs($this->employee)->get($form->url())->assertNotFound();
$this->post($form->url(), ['answers' => []])->assertNotFound();
$this->get('/formulare')->assertInertia(fn (Assert $p) => $p->where('forms', []));
Audiences::sync('form', $form->id, []);
$this->travel(2)->days();
$this->post($form->url(), ['answers' => ['name' => 'x', 'art' => 'Seminar', 'zustimmung' => '1']])->assertSessionHasErrors('form');
$this->get('/formulare')->assertInertia(fn (Assert $p) => $p->where('forms', []));
}
public function test_confidential_forms_leave_answers_out_of_the_mail(): void
{
$form = $this->trainingForm(['mail_answers' => false]);
$submission = $form->submissions()->create(['user_id' => $this->employee->id, 'data' => ['name' => ['label' => 'Name', 'type' => 'text', 'value' => 'Geheim']]]);
$html = (new FormSubmitted($form, $submission, $this->employee, false))->render();
$this->assertStringNotContainsString('Geheim', $html);
$this->assertStringContainsString('/admin/formulare/'.$form->id.'/ergebnisse', $html);
}
public function test_retention_deletes_old_submissions_with_files(): void
{
$form = $this->trainingForm(['retention_days' => 30]);
$old = $form->submissions()->create(['data' => []]);
$old->forceFill(['created_at' => now()->subDays(40)])->save();
Storage::disk('local')->put('forms/'.$form->id.'/alt.pdf', 'x');
$old->files()->create(['field' => 'nachweis', 'name' => 'alt.pdf', 'path' => 'forms/'.$form->id.'/alt.pdf']);
$form->submissions()->create(['data' => []]);
$this->assertSame(1, app(Retention::class)->purge());
$this->assertSame(1, $form->submissions()->count());
Storage::disk('local')->assertMissing('forms/'.$form->id.'/alt.pdf');
}
public function test_admin_creates_a_form_and_edits_fields_in_the_visual_builder(): void
{
$this->actingAs(User::factory()->admin()->create());
$hr = Role::query()->create(['name' => 'Personal']);
Livewire::test(CreateForm::class)
->fillForm([
'title' => 'Urlaubsantrag',
'settings' => ['notify_emails' => ['personal@firma.de'], 'mail_answers' => true],
'result_viewers' => [$hr->id],
])
->call('create')
->assertHasNoFormErrors()
->assertRedirect(route('forms.builder', Form::query()->sole()));
$form = Form::query()->sole();
$this->assertSame(['personal@firma.de'], $form->setting('notify_emails'));
$this->assertTrue(User::factory()->withRoles([$hr])->create()->can('viewResults', $form));
$this->get(route('forms.builder', $form))->assertOk()->assertInertia(fn (Assert $p) => $p
->component('forms::Builder')
->where('form.title', 'Urlaubsantrag')
->has('types', 13));
$fields = [
['type' => 'date', 'data' => ['label' => 'Von', 'required' => true, 'width' => 'half', 'evil' => '<script>']],
['type' => 'date', 'data' => ['label' => 'Bis', 'required' => true, 'width' => 'half']],
['type' => 'radio', 'data' => ['label' => 'Art', 'options' => ['Erholung', 'Sonderurlaub', '', 'Erholung']]],
['type' => 'textarea', 'data' => ['label' => 'Grund', 'condition_field' => 'art', 'condition_operator' => 'equals', 'condition_value' => 'Sonderurlaub', 'prefill' => 'name']],
];
$saved = $this->putJson(route('forms.builder.update', $form), ['title' => 'Urlaubsantrag 2027', 'description' => 'Bitte rechtzeitig.', 'fields' => $fields])
->assertOk()->json('fields');
$this->assertSame(['von', 'bis', 'art', 'grund'], array_column(array_column($saved, 'data'), 'key'));
$this->assertSame(['Erholung', 'Sonderurlaub'], $saved[2]['data']['options'], 'Leere und doppelte Optionen fallen weg.');
$this->assertArrayNotHasKey('evil', $saved[0]['data']);
$this->assertTrue($saved[0]['data']['required']);
$this->assertSame('half', $saved[0]['data']['width']);
$this->assertSame(['art', 'equals', 'Sonderurlaub'], [$saved[3]['data']['condition_field'], $saved[3]['data']['condition_operator'], $saved[3]['data']['condition_value']]);
$this->assertArrayNotHasKey('prefill', $saved[3]['data'], 'Vorbelegung gibt es nur für Text, E-Mail und Telefon.');
$this->assertSame('Urlaubsantrag 2027', $form->fresh()->title);
// Umbenennen behält den Schlüssel – alte Einsendungen bleiben zuordenbar.
$saved[0]['data']['label'] = 'Erster Urlaubstag';
$again = $this->putJson(route('forms.builder.update', $form), ['title' => 'Urlaubsantrag 2027', 'fields' => $saved])->json('fields');
$this->assertSame('von', $again[0]['data']['key']);
$this->putJson(route('forms.builder.update', $form), ['title' => 'x', 'fields' => [['type' => 'select', 'data' => ['label' => 'Leer', 'options' => []]]]])
->assertUnprocessable()->assertJsonValidationErrors('fields.0');
$this->putJson(route('forms.builder.update', $form), ['title' => 'x', 'fields' => [['type' => 'text', 'data' => ['label' => '']]]])
->assertUnprocessable();
}
public function test_only_editors_open_the_builder(): void
{
$form = $this->trainingForm();
$viewer = User::factory()->withRoles([$this->resultsRole($form)])->create();
$this->actingAs($viewer)->get(route('forms.builder', $form))->assertForbidden();
$this->putJson(route('forms.builder.update', $form), ['title' => 'x', 'fields' => []])->assertForbidden();
$editors = Role::query()->create(['name' => 'Formular-Redaktion']);
$editors->grants()->create(['ability' => 'forms.edit', 'resource_type' => 'form', 'resource_id' => $form->id]);
$this->actingAs(User::factory()->withRoles([$editors])->create())->get(route('forms.builder', $form))->assertOk()
->assertInertia(fn (Assert $p) => $p->where('resultsUrl', null));
$this->get('/redaktion')->assertInertia(fn (Assert $p) => $p->where('sections', fn ($sections) => collect($sections)->contains(fn ($s) => $s['key'] === 'forms'
&& $s['props']['forms'][0]['builder_url'] !== null && $s['props']['forms'][0]['csv_url'] === null)));
}
public function test_selected_results_can_be_downloaded_as_csv(): void
{
$form = $this->trainingForm();
$a = $form->submissions()->create(['data' => ['name' => ['label' => 'Name', 'type' => 'text', 'value' => 'Erste']]]);
$form->submissions()->create(['data' => ['name' => ['label' => 'Name', 'type' => 'text', 'value' => 'Zweite']]]);
$this->actingAs(User::factory()->withRoles([$this->resultsRole($form)])->create());
$csv = $this->get(route('forms.export', ['form' => $form, 'ids' => [$a->id]]))->assertOk()->streamedContent();
$this->assertStringContainsString('Erste', $csv);
$this->assertStringNotContainsString('Zweite', $csv);
}
public function test_forms_are_not_in_the_portal_menu(): void
{
$this->trainingForm();
$this->actingAs($this->employee)->get('/')->assertInertia(fn (Assert $p) => $p->where('navigation', fn ($items) => ! collect($items)->contains('key', 'forms')));
$this->get('/formulare/antrag-auf-fortbildung')->assertOk();
}
public function test_form_block_in_pages(): void
{
$form = $this->trainingForm();
$content = app(Content::class);
$rendered = $content->render($content->sanitize(['blocks' => [['type' => 'forms.form', 'data' => ['form' => (string) $form->id]]]]), $this->employee);
$this->assertSame('Antrag auf Fortbildung', $rendered['blocks'][0]['props']['title']);
$this->assertSame('forms::FormBlock', $rendered['blocks'][0]['component']);
Audiences::sync('form', $form->id, ['department' => ['Verwaltung']]);
$this->assertSame([], $content->render($content->sanitize(['blocks' => [['type' => 'forms.form', 'data' => ['form' => (string) $form->id]]]]), $this->employee)['blocks']);
}
public function test_locked_profile_fields_always_use_the_profile_value(): void
{
ProfileField::query()->create(['key' => 'personalnummer', 'label' => 'Personalnummer', 'editable' => false]);
$this->employee->update(['custom_fields' => ['personalnummer' => 'P-4711'], 'location' => null]);
$form = Form::query()->create(['title' => 'Stammdaten', 'fields' => [
['type' => 'text', 'data' => ['label' => 'Vorname', 'prefill' => 'first_name', 'locked' => true, 'required' => true]],
['type' => 'text', 'data' => ['label' => 'Personalnummer', 'prefill' => 'custom.personalnummer', 'locked' => true, 'required' => true]],
['type' => 'text', 'data' => ['label' => 'Standort', 'prefill' => 'location', 'locked' => true, 'required' => true]],
['type' => 'text', 'data' => ['label' => 'Abteilung', 'prefill' => 'department']],
]]);
$this->actingAs($this->employee)->get($form->url())->assertInertia(fn (Assert $p) => $p
->where('form.fields.0.locked', true)
->where('form.fields.1.locked', true)
->where('form.prefill.personalnummer', 'P-4711')
->missing('form.fields.3.locked'));
// Standort fehlt im Profil → Hinweis statt Einsendung.
$this->post($form->url(), ['answers' => ['vorname' => 'Gefälscht', 'personalnummer' => 'X-0000']])
->assertSessionHasErrors(['answers.standort' => 'Diese Angabe fehlt in Ihrem Profil. Bitte ergänzen Sie sie dort (Profil bearbeiten) oder wenden Sie sich an die Personalverwaltung.']);
$this->employee->update(['location' => 'Hamburg']);
$this->post($form->url(), ['answers' => ['vorname' => 'Gefälscht', 'personalnummer' => 'X-0000', 'abteilung' => 'Selbst geändert']])->assertSessionHasNoErrors();
$submission = FormSubmission::query()->sole();
$this->assertSame('Anna', $submission->display('vorname'), 'Manipulierte Eingaben werden durch den Profilwert ersetzt.');
$this->assertSame('P-4711', $submission->display('personalnummer'));
$this->assertSame('Hamburg', $submission->display('standort'));
$this->assertSame('Selbst geändert', $submission->display('abteilung'), 'Nur vorbelegte Felder bleiben änderbar.');
}
public function test_builder_keeps_lock_only_with_prefill(): void
{
$this->actingAs(User::factory()->admin()->create());
$form = $this->trainingForm();
$saved = $this->putJson(route('forms.builder.update', $form), ['title' => 'x', 'fields' => [
['type' => 'text', 'data' => ['label' => 'Vorname', 'prefill' => 'first_name', 'locked' => true]],
['type' => 'text', 'data' => ['label' => 'Frei', 'locked' => true]],
['type' => 'textarea', 'data' => ['label' => 'Text', 'prefill' => 'name', 'locked' => true]],
]])->assertOk()->json('fields');
$this->assertTrue($saved[0]['data']['locked']);
$this->assertArrayNotHasKey('locked', $saved[1]['data']);
$this->assertArrayNotHasKey('locked', $saved[2]['data']);
}
}