Loheide-eu-mitarbeiterplatt.../tests/Feature/ItService/ItServiceTest.php
Friederich Loheide c495dfa1cb
Some checks failed
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 3m29s
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 3m31s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 3m56s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 4m2s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 5m20s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 5m22s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 4m42s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 4m41s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m18s
Backend: eigenes kompaktes Theme, Übersicht, Cluster mit Unterseiten, Plugin-Liste
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 20:50:17 +00:00

247 lines
13 KiB
PHP
Raw Permalink 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\ItService;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Inertia\Testing\AssertableInertia as Assert;
use Inhaus\Plugins\ItService\Filament\Pages\ItServiceSettings;
use Inhaus\Plugins\ItService\OpenNit\Settings;
use Livewire\Livewire;
use Tests\TestCase;
class ItServiceTest extends TestCase
{
use RefreshDatabase;
private const BASE = 'https://itdoku.example.de/api/ex';
private User $user;
protected function setUp(): void
{
parent::setUp();
app(Settings::class)->save(['url' => self::BASE, 'token' => 'tok-123', 'secret' => 'geheim', 'auto_reserve' => 'default', 'intro' => null]);
$this->user = User::factory()->create(['first_name' => 'Max', 'last_name' => 'Muster', 'email' => 'Max.Muster@Example.com']);
}
/** Signatur nach der OpenNIT-Doku unabhängig nachrechnen */
private function assertSigned(Request $request, string $email): void
{
$url = parse_url($request->url());
parse_str($url['query'] ?? '', $query);
ksort($query);
$canonical = implode("\n", ['v2', $request->method(), $url['path'], http_build_query($query), strtolower($email), hash('sha256', $request->body()), $request->header('X-OpenNIT-Timestamp')[0], $request->header('X-OpenNIT-Nonce')[0]]);
$this->assertSame('Bearer tok-123', $request->header('Authorization')[0]);
$this->assertMatchesRegularExpression('/^[0-9a-f]{32}$/', $request->header('X-OpenNIT-Nonce')[0]);
$this->assertSame(hash_hmac('sha256', $canonical, 'geheim'), $request->header('X-OpenNIT-Signature')[0]);
}
public function test_overview_loads_own_assets_tickets_and_loans(): void
{
Http::fake([
'*/my-assets*' => Http::response(['assets' => [['id' => 5, 'name' => 'ThinkPad X1', 'serial' => 'PF-123', 'warranty_end' => '2027-12-31']]]),
'*/my-tickets*' => Http::response(['tickets' => [
['id' => 1, 'subject' => 'Alt', 'status' => 'closed', 'created_at' => '2026-01-10 08:00'],
['id' => 42, 'subject' => 'Drucker druckt nicht', 'status' => 'open', 'created_at' => '2026-04-17 10:30'],
]]),
'*/my-loans*' => Http::response(['loans' => [['id' => 99, 'device_title' => 'Beamer', 'status' => 'reserved', 'planned_start' => '2026-10-20', 'planned_end' => '2026-10-21']]]),
]);
$this->actingAs($this->user)->get('/it-service')->assertOk()->assertInertia(fn (Assert $page) => $page
->component('it-service::Index')
->where('configured', true)
->loadDeferredProps(fn (Assert $reload) => $reload
->where('assets.data.0.name', 'ThinkPad X1')
->where('tickets.data.0.subject', 'Drucker druckt nicht', 'offene Tickets zuerst')
->where('tickets.data.0.status_label', 'Offen')
->where('loans.data.0.status_label', 'Reserviert')
->where('loans.data.0.cancellable', true)));
Http::assertSent(function (Request $request) {
if (! str_contains($request->url(), '/my-tickets')) {
return false;
}
$this->assertStringContainsString('email=Max.Muster%40Example.com', $request->url());
$this->assertSigned($request, 'max.muster@example.com');
return true;
});
}
public function test_ticket_is_created_with_the_own_address_and_optional_device(): void
{
Http::fake([
'*/tickets' => Http::response(['id' => 42, 'status' => 'open']),
'*/ticket-categories' => Http::response(['categories' => [['id' => 3, 'name' => 'Hardware', 'parent_id' => null]]]),
'*/ticket-locations' => Http::response(['locations' => [['id' => 1, 'name' => 'Hauptgebäude', 'parent_id' => null]]]),
]);
// Kategorie und Standort sind Pflicht, wenn OpenNIT welche anbietet
$this->actingAs($this->user)->post('/it-service/tickets', ['subject' => 'X', 'description' => 'Y'])->assertSessionHasErrors(['category_id', 'location_id']);
$this->actingAs($this->user)->post('/it-service/tickets', [
'subject' => 'Bildschirm flackert',
'description' => 'Seit heute Morgen.',
'asset_id' => 5,
'category_id' => 3,
'location_id' => 1,
])->assertRedirect('/it-service/tickets/42');
Http::assertSent(function (Request $request) {
if ($request->method() !== 'POST') {
return false;
}
$body = json_decode($request->body(), true);
$this->assertSame(['subject' => 'Bildschirm flackert', 'from_email' => 'Max.Muster@Example.com', 'from_name' => 'Max Muster', 'description' => 'Seit heute Morgen.', 'category_id' => 3, 'location_id' => 1, 'asset_id' => 5], $body);
$this->assertSigned($request, ''); // „from_email“ ist nicht „email“ – E-Mail-Zeile leer
return $request->method() === 'POST';
});
}
public function test_ticket_detail_reply_and_foreign_tickets(): void
{
Http::fake([
'*/tickets/42/reply' => Http::response(['success' => true]),
'*/tickets/42*' => Http::response([
'ticket' => ['id' => 42, 'subject' => 'Drucker', 'status' => 'in_progress', 'description' => 'Geht nicht', 'created_at' => '2026-04-17 10:30'],
'replies' => [['message' => 'Wir schauen es uns an.', 'author' => 'IT-Team', 'is_staff' => true], ['message' => 'Intern', 'internal' => true]],
'attachments' => [['id' => 7, 'name' => 'fehler.png', 'size' => 2048]],
'assignees' => [['name' => 'Tom Technik']],
]),
'*/tickets/43*' => Http::response(['error' => 'not found'], 404),
]);
$this->actingAs($this->user)->get('/it-service/tickets/42')->assertOk()->assertInertia(fn (Assert $page) => $page
->component('it-service::Ticket')
->where('ticket.status_label', 'In Bearbeitung')
->has('ticket.replies', 1) // interne Notizen bleiben verborgen
->where('ticket.replies.0.from_staff', true)
->where('ticket.attachments.0.name', 'fehler.png')
->where('ticket.assignees', ['Tom Technik']));
$this->actingAs($this->user)->get('/it-service/tickets/43')->assertNotFound();
$this->actingAs($this->user)->from('/it-service/tickets/42')->post('/it-service/tickets/42/antworten', ['message' => 'Danke!'])->assertRedirect('/it-service/tickets/42');
Http::assertSent(function (Request $request) {
if (! str_ends_with($request->url(), '/reply')) {
return false;
}
$this->assertSame(['email' => 'Max.Muster@Example.com', 'message' => 'Danke!'], json_decode($request->body(), true));
$this->assertSigned($request, 'max.muster@example.com');
return true;
});
}
public function test_loan_request_uses_the_configured_reservation_mode_and_conflicts_are_shown(): void
{
app(Settings::class)->save(['url' => self::BASE, 'auto_reserve' => 'yes', 'intro' => null]);
Http::fakeSequence('*/loan-requests')
->push(['success' => true, 'lending_id' => 99, 'status' => 'reserved'])
->push(['error' => 'Gerät nicht verfügbar'], 409);
$data = ['device_id' => 4, 'planned_start' => now()->addDay()->toDateString(), 'planned_end' => now()->addDays(3)->toDateString(), 'purpose' => 'Fachtag'];
$this->actingAs($this->user)->post('/it-service/leihgeraete/anfragen', $data)->assertRedirect('/it-service')->assertSessionHas('status', 'Leihgerät reserviert. Die Übergabe organisiert die IT.');
$this->actingAs($this->user)->post('/it-service/leihgeraete/anfragen', $data)->assertSessionHasErrors(['planned_start' => 'Gerät nicht verfügbar']);
Http::assertSent(fn (Request $request) => json_decode($request->body(), true) === [
'device_id' => 4, 'planned_start' => $data['planned_start'], 'planned_end' => $data['planned_end'],
'borrower_name' => 'Max Muster', 'borrower_email' => 'Max.Muster@Example.com', 'purpose' => 'Fachtag', 'auto_reserve' => true,
]);
}
public function test_unreachable_or_unconfigured_service_degrades_gracefully(): void
{
Http::fake(['*' => Http::response('', 500)]);
$this->actingAs($this->user)->get('/it-service')->assertOk()->assertInertia(fn (Assert $page) => $page
->loadDeferredProps(fn (Assert $reload) => $reload->where('tickets.ok', false)->where('tickets.error', 'Der IT-Service ist gerade nicht erreichbar. Bitte später erneut versuchen.')));
$this->actingAs($this->user)->getJson('/it-service/uebersicht')->assertStatus(503);
app(\App\Support\Settings::class)->set(Settings::URL, '');
$this->actingAs($this->user)->get('/it-service')->assertInertia(fn (Assert $page) => $page->where('configured', false));
$this->assertNull($this->dashboardWidget($this->actingAs($this->user)->get('/'), 'it-service.summary'));
}
public function test_server_address_without_api_path_and_html_answers(): void
{
app(Settings::class)->save(['url' => 'https://itdoku.example.de/', 'auto_reserve' => 'default', 'intro' => null]);
$this->assertSame('https://itdoku.example.de/api/ex', app(Settings::class)->url(), '„/api/ex“ wird ergänzt');
Http::fake(['*' => Http::response('<!DOCTYPE html><html>Anmeldung</html>', 200, ['Content-Type' => 'text/html'])]);
$this->actingAs($this->user)->get('/it-service/leihgeraete')->assertInertia(fn (Assert $page) => $page
->where('devices.ok', false)
->where('devices.error', fn ($error) => str_contains($error, '/api/ex')));
Http::assertSent(fn (Request $request) => str_starts_with($request->url(), 'https://itdoku.example.de/api/ex/'));
}
public function test_closed_tickets_html_replies_error_messages_and_tree(): void
{
Http::fake([
'*/tickets/50*' => Http::response([
'ticket' => ['id' => 50, 'subject' => 'Laptop', 'status' => 'solved', 'description' => "Zeile 1\nZeile 2"],
'replies' => [['message' => '<br><br>Viele Grüße<br>Friederich<script>alert(1)</script>', 'from_email' => 'Max.Muster@Example.com']],
]),
'*/loan-requests' => Http::response(['error' => 'Der Zeitraum darf höchstens 14 Tage lang sein.'], 422),
'*/ticket-categories' => Http::response(['categories' => [
['id' => 1, 'name' => 'Hardware', 'parent_id' => null], ['id' => 2, 'name' => 'Drucker', 'parent_id' => 1],
['id' => 3, 'name' => 'Toner', 'parent_id' => 2], ['id' => 9, 'name' => 'Verwaist', 'parent_id' => 77],
]]),
'*/ticket-locations' => Http::response(['locations' => []]),
'*/my-assets*' => Http::response(['assets' => []]),
]);
$this->actingAs($this->user)->get('/it-service/tickets/50')->assertInertia(fn (Assert $page) => $page
->where('ticket.status_label', 'Gelöst')
->where('ticket.open', false)
->where('ticket.description', "Zeile 1<br>\nZeile 2")
->where('ticket.replies.0.message', fn ($html) => str_contains($html, 'Viele Grüße<br') && ! str_contains($html, 'script')));
$this->actingAs($this->user)->post('/it-service/tickets/50/antworten', ['message' => 'Noch da?'])->assertSessionHasErrors('message');
Http::assertNotSent(fn (Request $request) => str_ends_with($request->url(), '/reply'));
$this->actingAs($this->user)->post('/it-service/leihgeraete/anfragen', ['device_id' => 1, 'planned_start' => now()->addDay()->toDateString(), 'planned_end' => now()->addDays(40)->toDateString()])
->assertSessionHasErrors(['planned_start' => 'Der Zeitraum darf höchstens 14 Tage lang sein.']);
$this->actingAs($this->user)->get('/it-service/tickets/neu')->assertInertia(fn (Assert $page) => $page
->where('options.data.categories', fn ($categories) => collect($categories)->pluck('path')->all() === ['Hardware', 'Hardware › Drucker', 'Hardware › Drucker › Toner', 'Verwaist'])
->where('options.data.categories.2.depth', 2));
}
public function test_greeting_box_gets_a_my_it_button(): void
{
$actions = $this->dashboardWidget($this->actingAs($this->user)->get('/'), 'core.greeting')['actions'];
$this->assertSame([['label' => 'Meine IT', 'href' => '/it-service', 'icon' => 'monitor-smartphone']], $actions);
}
public function test_settings_keep_secrets_encrypted_and_only_admins_configure(): void
{
Livewire::actingAs(User::factory()->admin()->create())
->test(ItServiceSettings::class)
->set('data.url', 'https://it.example.org/api/ex')
->set('data.token', '')
->set('data.secret', 'neu-geheim')
->set('data.auto_reserve', 'no')
->call('save')
->assertHasNoErrors();
$settings = app(Settings::class);
$this->assertSame('tok-123', $settings->token(), 'leer gelassen = unverändert');
$this->assertSame('neu-geheim', $settings->secret());
$this->assertFalse($settings->autoReserve());
$this->assertStringNotContainsString('neu-geheim', (string) Setting::query()->where('key', Settings::SECRET)->value('value'));
$this->actingAs($this->user)->get('/admin/module/it-service')->assertForbidden();
}
}