Neues Plugin IT-Service (OpenNIT); Abteilung bei „Geschrieben von“
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 4m42s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 4m27s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 4m41s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 4m32s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 6m7s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 6m29s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 5m33s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m30s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 5m35s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 20:05:41 +00:00
parent c713194a83
commit c1117829c3
139 changed files with 2455 additions and 398 deletions

View file

@ -0,0 +1,135 @@
<?php
namespace Inhaus\Plugins\ItService\Filament\Pages;
use App\Support\Audit;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Inhaus\Plugins\ItService\OpenNit\Client;
use Inhaus\Plugins\ItService\OpenNit\OpenNitException;
use Inhaus\Plugins\ItService\OpenNit\Settings;
use UnitEnum;
class ItServiceSettings extends Page
{
protected string $view = 'filament.pages.settings-form';
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedLifebuoy;
protected static string|UnitEnum|null $navigationGroup = 'Portal';
protected static ?int $navigationSort = 60;
protected static ?string $navigationLabel = 'IT-Service';
protected static ?string $title = 'IT-Service (OpenNIT)';
protected static ?string $slug = 'it-service';
/** @var array<string, mixed>|null */
public ?array $data = [];
public static function canAccess(): bool
{
return auth()->user()?->can('it-service.manage') ?? false;
}
public function mount(Settings $settings): void
{
$this->form->fill([
'url' => $settings->url(),
'token' => null,
'secret' => null,
'auto_reserve' => match ($settings->autoReserve()) {
true => 'yes', false => 'no', null => 'default'
},
'intro' => $settings->intro(),
]);
}
public function form(Schema $schema): Schema
{
$settings = app(Settings::class);
return $schema->statePath('data')->components([
Section::make('Verbindung zu OpenNIT')
->description('Token und Signing-Secret erzeugen Sie in OpenNIT unter /admin/api (Token-Verwaltung) mit den Scopes „tickets“, „assets“ und „loans“. Beide werden verschlüsselt gespeichert. Die Zuordnung zu Personen erfolgt über die E-Mail-Adresse im Portal.')
->schema([
TextInput::make('url')
->label('API-Adresse')
->placeholder('https://itdoku.example.de/api/ex')
->url()
->required()
->regex('#^https://#i')
->validationMessages(['regex' => 'Die API ist nur über HTTPS erreichbar.']),
TextInput::make('token')
->label('Token')
->password()
->revealable()
->placeholder($settings->token() !== '' ? '•••••••• (gespeichert – leer lassen, um ihn zu behalten)' : '')
->required(fn () => $settings->token() === ''),
TextInput::make('secret')
->label('Signing-Secret')
->password()
->revealable()
->placeholder($settings->secret() !== '' ? '•••••••• (gespeichert – leer lassen, um es zu behalten)' : '')
->required(fn () => $settings->secret() === ''),
]),
Section::make('Leihgeräte')
->schema([
Select::make('auto_reserve')
->label('Anfragen aus dem Portal')
->options([
'default' => 'Wie in OpenNIT eingestellt',
'no' => 'Immer als Anfrage – die IT bestätigt',
'yes' => 'Sofort fest reservieren',
])
->selectablePlaceholder(false)
->default('default'),
]),
Section::make('Hinweistext')
->description('Erscheint oben auf „Meine IT“, z. B. Telefonnummer der IT-Hotline oder Servicezeiten.')
->schema([
RichEditor::make('intro')->hiddenLabel()->toolbarButtons([['bold', 'italic', 'link'], ['bulletList'], ['undo', 'redo']]),
]),
]);
}
public function save(Settings $settings): void
{
$data = $this->form->getState();
$settings->save($data);
Audit::log('it-service.settings', ['url' => $settings->url()]);
Notification::make()->success()->title('IT-Service gespeichert')->send();
$this->mount($settings);
}
protected function getHeaderActions(): array
{
return [
Action::make('test')
->label('Verbindung testen')
->icon(Heroicon::OutlinedSignal)
->color('gray')
->action(function (Client $client) {
try {
$categories = count((array) ($client->get('/ticket-categories')['categories'] ?? []));
$types = count((array) ($client->get('/device-types')['types'] ?? []));
Notification::make()->success()->title('Verbindung klappt')->body("{$categories} Ticket-Kategorien und {$types} Gerätetypen gefunden.")->send();
} catch (OpenNitException $e) {
Notification::make()->danger()->title('Keine Verbindung')->body($e->getMessage().($e->status ? " (HTTP {$e->status})" : ''))->persistent()->send();
}
}),
Action::make('portal')->label('Meine IT ansehen')->icon(Heroicon::OutlinedEye)->color('gray')->url('/it-service')->openUrlInNewTab(),
];
}
}

View file

@ -0,0 +1,194 @@
<?php
namespace Inhaus\Plugins\ItService\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Support\RichText;
use Closure;
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\ItService\ItService;
use Inhaus\Plugins\ItService\OpenNit\OpenNitException;
use Inhaus\Plugins\ItService\OpenNit\Settings;
use Symfony\Component\HttpFoundation\Response as HttpResponse;
/**
* „Meine IT“: Geräte, Tickets und Leihgeräte der angemeldeten Person aus OpenNIT.
*/
class ItServiceController extends Controller
{
public function __construct(private readonly ItService $it, private readonly Settings $settings) {}
public function index(Request $request): Response
{
$user = $request->user();
return Inertia::render('it-service::Index', [
'configured' => $this->it->configured(),
'intro' => $this->settings->intro() ? app(RichText::class)->sanitize($this->settings->intro()) : null,
// Jeder Bereich einzeln: fällt einer aus, bleiben die anderen sichtbar
'assets' => Inertia::defer(fn () => $this->attempt(fn () => $this->it->assets($user))),
'tickets' => Inertia::defer(fn () => $this->attempt(fn () => $this->it->tickets($user))),
'loans' => Inertia::defer(fn () => $this->attempt(fn () => $this->it->loans($user))),
]);
}
/** Zahlen für die Startseiten-Kachel (lädt die Kachel selbst nach) */
public function summary(Request $request): JsonResponse
{
$user = $request->user();
try {
$tickets = $this->it->tickets($user);
$loans = $this->it->loans($user);
} catch (OpenNitException $e) {
return response()->json(['message' => $e->getMessage()], 503);
}
return response()->json([
'open_tickets' => count(array_filter($tickets, fn ($t) => $t['open'])),
'latest' => array_slice(array_values(array_filter($tickets, fn ($t) => $t['open'])), 0, 3),
'loans' => count(array_filter($loans, fn ($l) => in_array($l['status'], ['pending', 'reserved', 'active'], true))),
]);
}
public function createTicket(Request $request): Response
{
$user = $request->user();
return Inertia::render('it-service::TicketCreate', [
'assetId' => $request->integer('geraet') ?: null,
'assets' => $this->attempt(fn () => $this->it->assets($user)),
'options' => $this->attempt(fn () => $this->it->ticketOptions()),
]);
}
public function storeTicket(Request $request): RedirectResponse
{
$data = $request->validate([
'subject' => ['required', 'string', 'max:200'],
'description' => ['required', 'string', 'max:20000'],
'category_id' => ['nullable', 'integer'],
'location_id' => ['nullable', 'integer'],
'asset_id' => ['nullable', 'integer'],
], [], ['subject' => 'Betreff', 'description' => 'Beschreibung']);
$id = $this->orFail(fn () => $this->it->createTicket($request->user(), $data), 'subject');
return $id > 0
? to_route('it-service.tickets.show', $id)->with('status', 'Ticket erstellt – die IT meldet sich.')
: to_route('it-service.index')->with('status', 'Ticket erstellt – die IT meldet sich.');
}
public function ticket(Request $request, int $id): Response
{
try {
$ticket = $this->it->ticket($request->user(), $id);
} catch (OpenNitException $e) {
abort($e->status === 404 || $e->status === 403 ? 404 : 503, $e->getMessage());
}
return Inertia::render('it-service::Ticket', ['ticket' => $ticket]);
}
public function reply(Request $request, int $id): RedirectResponse
{
$data = $request->validate(['message' => ['required', 'string', 'max:20000']], [], ['message' => 'Antwort']);
$this->orFail(fn () => $this->it->reply($request->user(), $id, $data['message']), 'message');
return back()->with('status', 'Antwort gesendet.');
}
public function attachment(Request $request, int $id): HttpResponse
{
try {
$file = $this->it->attachment($request->user(), $id);
} catch (OpenNitException $e) {
abort($e->status === 404 || $e->status === 403 ? 404 : 503, $e->getMessage());
}
$name = 'anhang-'.$id;
if (preg_match('/filename\*?=(?:UTF-8\'\')?"?([^";]+)"?/i', (string) $file->header('Content-Disposition'), $m)) {
$name = basename(rawurldecode($m[1]));
}
return response($file->body(), 200, [
'Content-Type' => $file->header('Content-Type') ?: 'application/octet-stream',
'Content-Disposition' => 'attachment; filename="'.addcslashes($name, '"\\').'"',
'X-Content-Type-Options' => 'nosniff',
]);
}
public function loanDevices(Request $request): Response
{
$filters = $request->validate([
'typ' => ['nullable', 'string', 'max:100'],
'von' => ['nullable', 'date_format:Y-m-d'],
'bis' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:von'],
]);
return Inertia::render('it-service::Loans', [
'filters' => ['type' => $filters['typ'] ?? null, 'from' => $filters['von'] ?? null, 'to' => $filters['bis'] ?? null],
'types' => $this->attempt(fn () => $this->it->deviceTypes()),
'devices' => $this->attempt(fn () => $this->it->loanDevices($filters['typ'] ?? null, $filters['von'] ?? null, $filters['bis'] ?? null)),
]);
}
public function slots(int $id): JsonResponse
{
try {
return response()->json(['slots' => $this->it->slots($id)]);
} catch (OpenNitException $e) {
return response()->json(['message' => $e->getMessage()], 503);
}
}
public function requestLoan(Request $request): RedirectResponse
{
$data = $request->validate([
'device_id' => ['required', 'integer'],
'planned_start' => ['required', 'date_format:Y-m-d', 'after_or_equal:today'],
'planned_end' => ['required', 'date_format:Y-m-d', 'after_or_equal:planned_start'],
'purpose' => ['nullable', 'string', 'max:500'],
], [], ['planned_start' => 'Beginn', 'planned_end' => 'Ende', 'purpose' => 'Zweck']);
$result = $this->orFail(fn () => $this->it->requestLoan($request->user(), $data), 'planned_start');
return to_route('it-service.index')->with('status', $result['status'] === 'reserved'
? 'Leihgerät reserviert. Die Übergabe organisiert die IT.'
: 'Anfrage gesendet – die IT bestätigt die Ausleihe.');
}
public function cancelLoan(Request $request, int $id): RedirectResponse
{
$this->orFail(fn () => $this->it->cancelLoan($request->user(), $id), 'loan');
return back()->with('status', 'Ausleihe storniert.');
}
/**
* @return array{ok: bool, data: mixed, error: ?string}
*/
private function attempt(Closure $callback): array
{
try {
return ['ok' => true, 'data' => $callback(), 'error' => null];
} catch (OpenNitException $e) {
return ['ok' => false, 'data' => null, 'error' => $e->getMessage()];
}
}
private function orFail(Closure $callback, string $field): mixed
{
try {
return $callback();
} catch (OpenNitException $e) {
throw ValidationException::withMessages([$field => $e->getMessage()]);
}
}
}

View file

@ -0,0 +1,312 @@
<?php
namespace Inhaus\Plugins\ItService;
use App\Models\User;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Arr;
use Inhaus\Plugins\ItService\OpenNit\Client;
use Inhaus\Plugins\ItService\OpenNit\Settings;
/**
* IT-Self-Service für eine Person: alle Abfragen laufen mit ihrer E-Mail-Adresse,
* OpenNIT liefert damit nur ihre eigenen Geräte, Tickets und Ausleihen.
* Antworten werden defensiv aufbereitet – die Oberfläche bekommt feste Felder.
*/
class ItService
{
public const OPEN_STATUSES = ['open', 'new', 'pending', 'in_progress', 'waiting', 'reopened', 'offen', 'neu', 'in_bearbeitung', 'wartend'];
public function __construct(private readonly Client $client, private readonly Settings $settings) {}
public function configured(): bool
{
return $this->settings->configured();
}
/**
* @return list<array<string, mixed>>
*/
public function assets(User $user): array
{
return array_map(fn (array $asset) => [
'id' => (int) ($asset['id'] ?? 0),
'name' => (string) ($asset['name'] ?? $asset['title'] ?? 'Gerät'),
'type' => self::text($asset, ['type', 'category', 'device_type']),
'serial' => self::text($asset, ['serial', 'serial_number']),
'inventory' => self::text($asset, ['inventory_number', 'asset_tag', 'inventory']),
'manufacturer' => self::text($asset, ['manufacturer', 'vendor']),
'model' => self::text($asset, ['model']),
'location' => self::text($asset, ['location', 'location_name']),
'warranty_end' => self::text($asset, ['warranty_end', 'warranty_until']),
'maintenance' => self::text($asset, ['next_maintenance', 'maintenance_due', 'maintenance']),
], $this->list($this->client->get('/my-assets', ['email' => $user->email]), 'assets'));
}
/**
* @return list<array<string, mixed>>
*/
public function tickets(User $user): array
{
$tickets = array_map(fn (array $ticket) => self::ticketSummary($ticket), $this->list($this->client->get('/my-tickets', ['email' => $user->email]), 'tickets'));
usort($tickets, fn ($a, $b) => [$b['open'], $b['created_at']] <=> [$a['open'], $a['created_at']]);
return $tickets;
}
/**
* @return array<string, mixed>
*/
public function ticket(User $user, int $id): array
{
$data = $this->client->get("/tickets/{$id}", ['email' => $user->email]);
$ticket = (array) ($data['ticket'] ?? $data);
return [
...self::ticketSummary($ticket),
'description' => self::text($ticket, ['description', 'body', 'message', 'text']),
'category' => self::text($ticket, ['category', 'category_name']),
'location' => self::text($ticket, ['location', 'location_name']),
'asset' => self::text($ticket, ['asset', 'asset_name']),
'replies' => array_map(fn ($reply) => [
'message' => is_array($reply) ? (string) (self::text($reply, ['message', 'body', 'text', 'content']) ?? '') : (string) $reply,
'author' => is_array($reply) ? self::text($reply, ['author', 'from_name', 'name', 'user', 'author_name']) : null,
'from_staff' => is_array($reply) && (bool) ($reply['is_staff'] ?? $reply['internal_user'] ?? $reply['from_staff'] ?? (isset($reply['from_email']) && mb_strtolower((string) $reply['from_email']) !== mb_strtolower($user->email))),
'created_at' => is_array($reply) ? self::text($reply, ['created_at', 'date', 'created']) : null,
], array_values(array_filter((array) ($data['replies'] ?? []), fn ($reply) => ! (is_array($reply) && ($reply['internal'] ?? $reply['is_internal'] ?? false))))),
'attachments' => array_values(array_filter(array_map(fn ($file) => is_array($file) && isset($file['id']) ? [
'id' => (int) $file['id'],
'name' => (string) ($file['name'] ?? $file['filename'] ?? $file['original_name'] ?? 'Anhang'),
'size' => isset($file['size']) ? (int) $file['size'] : null,
] : null, (array) ($data['attachments'] ?? [])))),
'assignees' => array_values(array_filter(array_map(fn ($person) => is_array($person) ? self::text($person, ['name', 'display_name', 'username']) : (is_string($person) ? $person : null), (array) ($data['assignees'] ?? [])))),
];
}
/**
* @param array{subject: string, description?: ?string, category_id?: ?int, location_id?: ?int, asset_id?: ?int} $data
*/
public function createTicket(User $user, array $data): int
{
$response = $this->client->post('/tickets', array_filter([
'subject' => $data['subject'],
'from_email' => $user->email,
'from_name' => $user->name,
'description' => $data['description'] ?? null,
'category_id' => $data['category_id'] ?? null,
'location_id' => $data['location_id'] ?? null,
'asset_id' => $data['asset_id'] ?? null,
], fn ($value) => $value !== null && $value !== ''));
return (int) ($response['id'] ?? $response['ticket_id'] ?? 0);
}
public function reply(User $user, int $ticketId, string $message): void
{
$this->client->post("/tickets/{$ticketId}/reply", ['email' => $user->email, 'message' => $message]);
}
public function attachment(User $user, int $id): Response
{
return $this->client->download("/ticket-attachments/{$id}", ['email' => $user->email]);
}
/**
* @return list<array<string, mixed>>
*/
public function loans(User $user): array
{
return array_map(fn (array $loan) => [
'id' => (int) ($loan['id'] ?? 0),
'device' => (string) ($loan['device_title'] ?? $loan['device'] ?? 'Leihgerät'),
'status' => (string) ($loan['status'] ?? ''),
'status_label' => self::loanStatus((string) ($loan['status'] ?? '')),
'start' => self::text($loan, ['planned_start', 'start']),
'end' => self::text($loan, ['planned_end', 'end']),
'cancellable' => in_array($loan['status'] ?? '', ['pending', 'reserved'], true),
], $this->list($this->client->get('/my-loans', ['email' => $user->email]), 'loans'));
}
/**
* @return list<array<string, mixed>>
*/
public function loanDevices(?string $type, ?string $from, ?string $to): array
{
return array_map(fn (array $device) => [
'id' => (int) ($device['id'] ?? 0),
'title' => (string) ($device['title'] ?? $device['name'] ?? 'Leihgerät'),
'type' => self::text($device, ['type', 'category']),
'available' => (bool) ($device['available'] ?? true),
'description' => self::text($device, ['description', 'notes']),
], $this->list($this->client->get('/loan-devices', ['type' => $type, 'date_from' => $from, 'date_to' => $to]), 'devices'));
}
/**
* @return list<array{start: string, end: string}>
*/
public function slots(int $deviceId): array
{
return array_values(array_filter(array_map(fn ($slot) => is_array($slot) && isset($slot['start']) ? ['start' => (string) $slot['start'], 'end' => (string) ($slot['end'] ?? $slot['start'])] : null, $this->list($this->client->get("/loan-devices/{$deviceId}/slots"), 'slots'))));
}
/**
* @param array{device_id: int, planned_start: string, planned_end: string, purpose?: ?string} $data
* @return array{status: string, message: ?string}
*/
public function requestLoan(User $user, array $data): array
{
$body = [
'device_id' => $data['device_id'],
'planned_start' => $data['planned_start'],
'planned_end' => $data['planned_end'],
'borrower_name' => $user->name,
'borrower_email' => $user->email,
'purpose' => $data['purpose'] ?? null,
];
if (($auto = $this->settings->autoReserve()) !== null) {
$body['auto_reserve'] = $auto;
}
$response = $this->client->post('/loan-requests', array_filter($body, fn ($value) => $value !== null));
return ['status' => (string) ($response['status'] ?? 'pending'), 'message' => is_string($response['message'] ?? null) ? $response['message'] : null];
}
public function cancelLoan(User $user, int $id): void
{
$this->client->post("/loan-requests/{$id}/cancel", ['email' => $user->email]);
}
/**
* @return array{categories: list<array<string, mixed>>, locations: list<array<string, mixed>>}
*/
public function ticketOptions(): array
{
return [
'categories' => self::tree($this->list($this->client->cached('/ticket-categories'), 'categories')),
'locations' => self::tree($this->list($this->client->cached('/ticket-locations'), 'locations')),
];
}
/**
* @return list<string>
*/
public function deviceTypes(): array
{
return array_values(array_filter(array_map(fn ($type) => is_string($type) ? $type : (is_array($type) ? ($type['name'] ?? null) : null), $this->list($this->client->cached('/device-types'), 'types'))));
}
/**
* @param array<string, mixed> $ticket
* @return array<string, mixed>
*/
private static function ticketSummary(array $ticket): array
{
$status = (string) ($ticket['status'] ?? '');
return [
'id' => (int) ($ticket['id'] ?? 0),
'subject' => (string) ($ticket['subject'] ?? $ticket['title'] ?? 'Ticket'),
'status' => $status,
'status_label' => self::ticketStatus($status),
'open' => self::isOpen($status),
'created_at' => self::text($ticket, ['created_at', 'created', 'date']) ?? '',
'updated_at' => self::text($ticket, ['updated_at', 'last_activity']),
'number' => self::text($ticket, ['number', 'ticket_number', 'reference']),
];
}
public static function isOpen(string $status): bool
{
return ! in_array(mb_strtolower($status), ['closed', 'resolved', 'done', 'geschlossen', 'erledigt', 'geloest', 'gelöst', 'cancelled'], true);
}
public static function ticketStatus(string $status): string
{
return match (mb_strtolower($status)) {
'open', 'new', 'offen', 'neu' => 'Offen',
'in_progress', 'in_bearbeitung', 'assigned' => 'In Bearbeitung',
'pending', 'waiting', 'wartend', 'on_hold' => 'Wartet auf Rückmeldung',
'reopened' => 'Wieder geöffnet',
'resolved', 'geloest', 'gelöst', 'done', 'erledigt' => 'Gelöst',
'closed', 'geschlossen' => 'Geschlossen',
'cancelled' => 'Storniert',
default => $status !== '' ? ucfirst(str_replace('_', ' ', $status)) : 'Offen',
};
}
public static function loanStatus(string $status): string
{
return match ($status) {
'pending' => 'Angefragt',
'reserved' => 'Reserviert',
'active' => 'Ausgeliehen',
'returned' => 'Zurückgegeben',
'rejected' => 'Abgelehnt',
'cancelled' => 'Storniert',
default => $status !== '' ? ucfirst($status) : 'Angefragt',
};
}
/**
* @param array<string, mixed> $data
* @return list<array<string, mixed>>
*/
private function list(array $data, string $key): array
{
$items = $data[$key] ?? (array_is_list($data) ? $data : []);
return array_values(array_filter((array) $items, fn ($item) => is_array($item) || is_string($item)));
}
/**
* Hierarchie (parent_id) als eingerückte Liste für Auswahlfelder.
*
* @param list<array<string, mixed>> $items
* @return list<array{value: int, label: string}>
*/
private static function tree(array $items): array
{
$children = [];
foreach ($items as $item) {
if (is_array($item) && isset($item['id'])) {
$children[$item['parent_id'] ?? 0][] = $item;
}
}
$result = [];
$walk = function ($parent, int $depth) use (&$walk, &$children, &$result) {
foreach ($children[$parent] ?? [] as $item) {
$result[] = ['value' => (int) $item['id'], 'label' => str_repeat('– ', $depth).($item['name'] ?? '')];
$walk($item['id'], $depth + 1);
}
};
$walk(0, 0);
return $result;
}
/**
* @param array<string, mixed> $data
* @param list<string> $keys
*/
private static function text(array $data, array $keys): ?string
{
foreach ($keys as $key) {
$value = Arr::get($data, $key);
if (is_array($value)) {
$value = $value['name'] ?? $value['title'] ?? null;
}
if (is_scalar($value) && trim((string) $value) !== '') {
return trim((string) $value);
}
}
return null;
}
}

View file

@ -0,0 +1,28 @@
<?php
namespace Inhaus\Plugins\ItService;
use App\Dashboard\Widgets;
use App\Plugins\Plugin;
use App\Support\Abilities;
use App\Support\Navigation;
use Inhaus\Plugins\ItService\OpenNit\Settings;
/**
* IT-Self-Service über OpenNIT (IT-Dokumentation): eigene Geräte, Tickets und Leihgeräte.
*/
class ItServicePlugin extends Plugin
{
public function register(): void
{
$this->app->singleton(Settings::class);
$this->app->make(Abilities::class)->define('it-service.manage', 'IT-Service (OpenNIT) einrichten', 'IT-Service');
$this->app->make(Navigation::class)->add('it-service', 'IT-Service', '/it-service', active: 'it-service.*', sort: 75);
// Die Kachel lädt ihre Zahlen selbst nach – die Startseite wartet nicht auf OpenNIT.
$this->app->make(Widgets::class)->add('it-service.summary', 'it-service::MyIt', 'aside', sort: 25,
props: fn () => app(Settings::class)->configured() ? [] : null,
label: 'Meine IT (offene Tickets, Ausleihen)', mobileSort: 45);
}
}

View file

@ -0,0 +1,158 @@
<?php
namespace Inhaus\Plugins\ItService\OpenNit;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
/**
* Zugriff auf die OpenNIT-API (/api/ex) mit Bearer-Token und HMAC-Signatur v2:
*
* v2 \n METHODE \n PFAD \n QUERY (sortiert) \n EMAIL (klein) \n sha256(BODY) \n TIMESTAMP \n NONCE
*
* Die E-Mail-Zeile bindet personenbezogene Abfragen („my-tickets“ …) an das
* Signing-Secret – so liefert OpenNIT nur Daten der angemeldeten Person.
*/
class Client
{
public function __construct(private readonly Settings $settings) {}
/**
* @param array<string, scalar|null> $query
* @param array<string, mixed>|null $body
* @return array<string, mixed>
*/
public function get(string $path, array $query = []): array
{
return $this->json($this->send('GET', $path, $query));
}
/**
* @param array<string, mixed> $body
* @return array<string, mixed>
*/
public function post(string $path, array $body = []): array
{
return $this->json($this->send('POST', $path, [], $body));
}
/**
* Binärantwort (z. B. Ticket-Anhang).
*
* @param array<string, scalar|null> $query
*/
public function download(string $path, array $query = []): Response
{
$response = $this->send('GET', $path, $query);
if (! $response->successful()) {
throw OpenNitException::fromStatus($response->status(), (array) $response->json());
}
return $response;
}
/**
* Stammdaten (Kategorien, Standorte, Gerätetypen) – kurz zwischengespeichert.
*
* @return array<string, mixed>
*/
public function cached(string $path, int $seconds = 600): array
{
return Cache::remember('it-service:'.md5($this->settings->url().$path), $seconds, fn () => $this->get($path));
}
/**
* Kanonische Zeichenkette der Signatur (öffentlich für Tests).
*
* @param array<string, scalar|null> $query
*/
public static function canonical(string $method, string $path, array $query, string $email, string $body, int $timestamp, string $nonce): string
{
ksort($query);
return implode("\n", [
'v2',
strtoupper($method),
$path,
http_build_query($query),
mb_strtolower($email),
hash('sha256', $body),
(string) $timestamp,
$nonce,
]);
}
/**
* @param array<string, scalar|null> $query
* @param array<string, mixed>|null $body
*/
private function send(string $method, string $path, array $query = [], ?array $body = null): Response
{
if (! $this->settings->configured()) {
throw new OpenNitException('Der IT-Service ist noch nicht eingerichtet. Bitte die Administration informieren.');
}
$query = array_filter($query, fn ($value) => $value !== null && $value !== '');
$base = $this->settings->url();
$basePath = rtrim((string) parse_url($base, PHP_URL_PATH), '/');
$fullPath = $basePath.'/'.ltrim($path, '/');
$raw = $body === null ? '' : json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$email = (string) ($query['email'] ?? (is_array($body) ? ($body['email'] ?? '') : ''));
$timestamp = time();
$nonce = bin2hex(random_bytes(16));
$signature = hash_hmac('sha256', self::canonical($method, $fullPath, $query, $email, $raw, $timestamp, $nonce), $this->settings->secret());
$request = Http::withToken($this->settings->token())
->withHeaders([
'X-OpenNIT-Timestamp' => (string) $timestamp,
'X-OpenNIT-Nonce' => $nonce,
'X-OpenNIT-Signature' => $signature,
'Accept' => 'application/json',
])
->timeout(15)
->connectTimeout(5);
$url = rtrim((string) preg_replace('#(https?://[^/]+).*#', '$1', $base), '/').$fullPath.($query ? '?'.http_build_query(self::sorted($query)) : '');
try {
return $body === null
? $request->send($method, $url)
: $request->withBody($raw, 'application/json')->send($method, $url);
} catch (ConnectionException $e) {
Log::warning('OpenNIT nicht erreichbar: '.$e->getMessage());
throw new OpenNitException('Der IT-Service ist gerade nicht erreichbar. Bitte später erneut versuchen.');
}
}
/**
* @return array<string, mixed>
*/
private function json(Response $response): array
{
$data = (array) $response->json();
if (! $response->successful()) {
Log::info("OpenNIT antwortete {$response->status()}", ['body' => mb_substr($response->body(), 0, 500)]);
throw OpenNitException::fromStatus($response->status(), $data);
}
return $data;
}
/**
* @param array<string, scalar|null> $query
* @return array<string, scalar|null>
*/
private static function sorted(array $query): array
{
ksort($query);
return $query;
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace Inhaus\Plugins\ItService\OpenNit;
use RuntimeException;
/**
* Fehler von OpenNIT – mit einer Meldung, die man Mitarbeitenden zeigen kann.
*/
class OpenNitException extends RuntimeException
{
public function __construct(string $message, public readonly int $status = 0, public readonly array $body = [])
{
parent::__construct($message, $status);
}
public static function fromStatus(int $status, array $body): self
{
$detail = is_string($body['message'] ?? null) ? $body['message'] : (is_string($body['error'] ?? null) ? $body['error'] : null);
$message = match ($status) {
400 => 'Die Angaben sind unvollständig oder ungültig.'.($detail ? " ({$detail})" : ''),
401 => 'Die Verbindung zum IT-Service ist nicht richtig eingerichtet (Anmeldung abgelehnt). Bitte die Administration informieren.',
403 => 'Der IT-Service erlaubt diesen Zugriff nicht.',
404 => 'Nicht gefunden – vielleicht gehört der Eintrag zu einer anderen Person.',
409 => $detail ?: 'Das Gerät ist in diesem Zeitraum nicht verfügbar.',
default => 'Der IT-Service ist gerade nicht erreichbar. Bitte später erneut versuchen.',
};
return new self($message, $status, $body);
}
}

View file

@ -0,0 +1,94 @@
<?php
namespace Inhaus\Plugins\ItService\OpenNit;
use App\Support\Settings as PortalSettings;
use Illuminate\Support\Facades\Crypt;
use Throwable;
/**
* Zugangsdaten zu OpenNIT. Token und Signing-Secret liegen verschlüsselt in den Einstellungen.
*/
class Settings
{
public const URL = 'it_service.url';
public const TOKEN = 'it_service.token';
public const SECRET = 'it_service.secret';
/** null = Einstellung in OpenNIT, true = sofort reservieren, false = immer Anfrage */
public const AUTO_RESERVE = 'it_service.auto_reserve';
public const INTRO = 'it_service.intro';
public function __construct(private readonly PortalSettings $settings) {}
public function url(): string
{
return rtrim((string) $this->settings->get(self::URL, ''), '/');
}
public function token(): string
{
return $this->decrypt(self::TOKEN);
}
public function secret(): string
{
return $this->decrypt(self::SECRET);
}
public function configured(): bool
{
return $this->url() !== '' && $this->token() !== '' && $this->secret() !== '';
}
public function autoReserve(): ?bool
{
$value = $this->settings->get(self::AUTO_RESERVE);
return $value === null ? null : (bool) $value;
}
public function intro(): ?string
{
return $this->settings->get(self::INTRO) ?: null;
}
/**
* @param array{url: string, token?: ?string, secret?: ?string, auto_reserve: ?string, intro: ?string} $data leere Token/Secret = unverändert
*/
public function save(array $data): void
{
$this->settings->set(self::URL, rtrim(trim($data['url']), '/'));
foreach ([self::TOKEN => $data['token'] ?? null, self::SECRET => $data['secret'] ?? null] as $key => $value) {
if (filled($value)) {
$this->settings->set($key, Crypt::encryptString(trim($value)));
}
}
$this->settings->set(self::AUTO_RESERVE, match ($data['auto_reserve'] ?? '') {
'yes' => true,
'no' => false,
default => null,
});
$this->settings->set(self::INTRO, $data['intro'] ?? null);
}
private function decrypt(string $key): string
{
$value = $this->settings->get($key);
if (! is_string($value) || $value === '') {
return '';
}
try {
return Crypt::decryptString($value);
} catch (Throwable) {
return '';
}
}
}