Rückmeldungen, Hintergrundaufgaben, Systemzustand und Web-Installer

- Rückmeldungen an den Hersteller (docs/specs/feedback.md): Fehlerbericht und
  Funktionswunsch, nur freigeschaltete Wege, Idempotency-Key je Meldung,
  Warteschlange mit höchstens fünf Versuchen, 422 am Feld, 429 mit Wartezeit,
  404 blendet den Weg aus, Referenznummer und „Meine Rückmeldungen“,
  sichtbare technische Angaben und Datenschutzhinweis über dem Absendeknopf
- Hintergrundaufgaben ohne Dauerprozess: Cron, Web-Cron (/cron/{token}) oder
  Pseudo-Cron nach dem Seitenaufruf; Queue in kurzen Häppchen
- Seite „Systemzustand“ mit Voraussetzungen, Grenzen, Betrieb, Sicherheit und
  Anleitung für den Cronjob
- Web-Installer (Systemprüfung → Datenbank → Administrator), legt .env und
  Anwendungsschlüssel selbst an, arbeitet vor der Einrichtung ohne Datenbank
- Datenbank-Benachrichtigungen im Admin-Bereich

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 06:11:09 +00:00
parent 43244d751a
commit 029dbd243d
38 changed files with 2274 additions and 12 deletions

View file

@ -0,0 +1,137 @@
<?php
namespace App\Filament\Pages;
use App\Models\VendorFeedback;
use App\Support\Audit;
use App\Support\Feedback\FeedbackChannels;
use App\Support\Feedback\FeedbackOutbox;
use App\Support\Feedback\FeedbackResult;
use App\Support\Feedback\TechnicalInfo;
use App\Support\License\LicenseStore;
use BackedEnum;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use UnitEnum;
/**
* „Hilfe → Rückmeldung geben“: Fehlerbericht oder Funktionswunsch an den
* Hersteller (docs/specs/feedback.md).
*/
class Feedback extends Page
{
protected string $view = 'filament.pages.feedback';
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedChatBubbleLeftEllipsis;
protected static string|UnitEnum|null $navigationGroup = 'Hilfe';
protected static ?string $navigationLabel = 'Rückmeldung geben';
protected static ?string $title = 'Rückmeldung geben';
protected static ?string $slug = 'rueckmeldung';
public string $type = '';
public string $subject = '';
public string $body = '';
public string $severity = 'normal';
public string $email = '';
public string $name = '';
public ?string $lastReference = null;
public ?string $notice = null;
public function mount(FeedbackChannels $channels): void
{
$this->type = (string) array_key_first($channels->available());
}
public function submit(FeedbackChannels $channels, FeedbackOutbox $outbox, TechnicalInfo $info): void
{
$available = $channels->available();
$this->validate([
'type' => ['required', 'in:'.implode(',', array_keys($available))],
'subject' => ['required', 'string', 'max:255'],
'body' => ['required', 'string', 'min:10', 'max:20000'],
'severity' => ['required', 'in:low,normal,high,critical'],
'email' => ['nullable', 'email', 'max:255'],
'name' => ['nullable', 'string', 'max:255'],
], attributes: [
'type' => 'Art der Meldung', 'subject' => 'Betreff', 'body' => 'Beschreibung',
'email' => 'E-Mail-Adresse', 'name' => 'Name',
]);
$this->notice = null;
$this->lastReference = null;
$payload = array_filter([
'title' => $this->subject,
'body' => $this->body,
'email' => $this->email ?: null,
'name' => $this->name ?: null,
'severity' => $this->type === 'bugreport' ? $this->severity : null,
...$info->collect(),
], fn ($value) => $value !== null);
$result = $outbox->submit(auth()->user(), $this->type, $payload);
switch ($result->status) {
case FeedbackResult::SENT:
Audit::log('feedback.sent', ['type' => $this->type, 'reference' => $result->reference]);
$this->lastReference = $result->reference;
$this->reset(['subject', 'body', 'severity']);
Notification::make()->success()->title('Vielen Dank – Ihre Meldung ist eingegangen')->body("Referenznummer: {$result->reference}")->persistent()->send();
break;
case FeedbackResult::RETRY:
$this->reset(['subject', 'body', 'severity']);
$this->notice = 'Der Server ist gerade nicht erreichbar. Ihre Meldung ist gespeichert und wird automatisch gesendet, sobald es wieder geht. Die Referenznummer erscheint dann unten in der Liste.';
break;
case FeedbackResult::INVALID:
// Fehler direkt am betroffenen Feld anzeigen (API-Feld „title“ = Formularfeld „subject“).
foreach ($result->errors as $field => $message) {
$field = $field === 'title' ? 'subject' : $field;
$this->addError(in_array($field, ['subject', 'body', 'email', 'name', 'severity'], true) ? $field : 'body', $message);
}
if ($result->errors === []) {
$this->addError('body', $result->message ?? 'Die Eingabe ist unvollständig.');
}
break;
case FeedbackResult::RATE_LIMITED:
$minutes = $result->retryAfter ? max(1, (int) ceil($result->retryAfter / 60)) : null;
$this->notice = 'Es wurden zu viele Meldungen in kurzer Zeit gesendet. Bitte versuchen Sie es '.($minutes ? "in etwa {$minutes} Minute(n)" : 'später').' noch einmal – Ihre Eingabe bleibt erhalten.';
break;
case FeedbackResult::DISABLED:
$channels->disable($this->type);
$this->notice = 'Dieser Meldeweg steht nicht mehr zur Verfügung. Ihre Eingabe bleibt erhalten'.(count($channels->available()) ? ' – bitte wählen Sie eine andere Art der Meldung.' : '.');
$this->type = (string) array_key_first($channels->available());
break;
}
}
/**
* @return array<string, mixed>
*/
protected function getViewData(): array
{
return [
'types' => app(FeedbackChannels::class)->available(),
'technical' => app(TechnicalInfo::class)->collect(),
'hasLicense' => app(LicenseStore::class)->hasLicense(),
'history' => VendorFeedback::query()->where('user_id', auth()->id())->latest()->limit(20)->get(),
];
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace App\Filament\Pages;
use App\Support\BackgroundTasks;
use App\Support\SiteHealth;
use BackedEnum;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use UnitEnum;
class SystemHealth extends Page
{
protected string $view = 'filament.pages.system-health';
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedHeart;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?int $navigationSort = 20;
protected static ?string $navigationLabel = 'Systemzustand';
protected static ?string $title = 'Systemzustand';
protected static ?string $slug = 'systemzustand';
/**
* @return array<string, mixed>
*/
protected function getViewData(): array
{
return [
'groups' => app(SiteHealth::class)->all(),
'cronLine' => '* * * * * cd '.base_path().' && php artisan schedule:run >> /dev/null 2>&1',
'webCronUrl' => url('/cron/'.app(BackgroundTasks::class)->webCronToken()),
];
}
}

View file

@ -0,0 +1,23 @@
<?php
namespace App\Http\Controllers;
use App\Support\BackgroundTasks;
use Illuminate\Http\Response;
/**
* Web-Cron für Hoster ohne Cron: ein externer Dienst ruft minütlich
* /cron/{token} auf.
*/
class CronController extends Controller
{
public function __invoke(string $token, BackgroundTasks $tasks): Response
{
abort_unless(hash_equals($tasks->webCronToken(), $token), 404);
@ignore_user_abort(true);
$tasks->run('webcron');
return response()->noContent();
}
}

View file

@ -0,0 +1,160 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Support\Audit;
use App\Support\EnvFile;
use App\Support\Installation;
use App\Support\License\LicenseStore;
use App\Support\Settings;
use App\Support\SiteHealth;
use App\Support\Update\Migrations;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Validation\Rules\Password;
use Illuminate\View\View;
use PDO;
use Throwable;
/**
* Web-Installer: Systemprüfung → Datenbank → Administrator. Nur erreichbar,
* solange die Installation nicht eingerichtet ist.
*/
class InstallController extends Controller
{
public function __construct()
{
abort_if(Installation::isInstalled(), 404);
}
public function requirements(SiteHealth $health): View
{
$checks = $health->requirements();
return view('install.requirements', [
'checks' => $checks,
'canContinue' => collect($checks)->doesntContain('status', SiteHealth::ERROR) && is_file(app()->environmentFilePath()),
'envWritable' => is_file(app()->environmentFilePath()) && is_writable(app()->environmentFilePath()),
]);
}
public function database(): View
{
return view('install.database', [
'values' => [
'host' => config('database.connections.mysql.host', 'localhost'),
'port' => config('database.connections.mysql.port', 3306),
'database' => config('database.connections.mysql.database'),
'username' => config('database.connections.mysql.username'),
],
]);
}
public function saveDatabase(Request $request): RedirectResponse
{
$data = $request->validate([
'host' => ['required', 'string', 'max:255'],
'port' => ['required', 'integer', 'between:1,65535'],
'database' => ['required', 'string', 'max:64'],
'username' => ['required', 'string', 'max:255'],
'password' => ['nullable', 'string', 'max:255'],
], attributes: ['host' => 'Server', 'port' => 'Port', 'database' => 'Datenbank', 'username' => 'Benutzer', 'password' => 'Passwort']);
try {
$pdo = new PDO(
"mysql:host={$data['host']};port={$data['port']};dbname={$data['database']};charset=utf8mb4",
$data['username'],
$data['password'] ?? '',
[PDO::ATTR_TIMEOUT => 5, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION],
);
$version = (string) $pdo->query('select version()')->fetchColumn();
} catch (Throwable $e) {
return back()->withInput($request->except('password'))
->withErrors(['host' => 'Verbindung fehlgeschlagen: '.$this->pdoMessage($e->getMessage())]);
}
$mariadb = str_contains(strtolower($version), 'mariadb');
$number = preg_replace('/^(\d+\.\d+\.\d+).*$/', '$1', $version);
if (! version_compare($number, $mariadb ? '10.6.0' : '8.0.0', '>=')) {
return back()->withInput($request->except('password'))
->withErrors(['host' => ($mariadb ? 'MariaDB ' : 'MySQL ').$number.' wird nicht unterstützt. Benötigt wird MySQL ab 8.0 oder MariaDB ab 10.6.']);
}
EnvFile::set(app()->environmentFilePath(), [
'APP_URL' => $request->getSchemeAndHttpHost().$request->getBaseUrl(),
'DB_CONNECTION' => 'mysql',
'DB_HOST' => $data['host'],
'DB_PORT' => (string) $data['port'],
'DB_DATABASE' => $data['database'],
'DB_USERNAME' => $data['username'],
'DB_PASSWORD' => $data['password'] ?? '',
]);
return redirect('/install/konto');
}
public function account(): View|RedirectResponse
{
return view('install.account');
}
public function saveAccount(Request $request, Settings $settings, LicenseStore $license, Migrations $migrations): RedirectResponse
{
$data = $request->validate([
'portal_name' => ['required', 'string', 'max:60'],
'first_name' => ['required', 'string', 'max:100'],
'last_name' => ['required', 'string', 'max:100'],
'email' => ['required', 'email', 'max:255'],
'password' => ['required', 'confirmed', Password::min(10)->letters()->numbers()],
'license_email' => ['nullable', 'email', 'max:255', 'required_with:license_key'],
'license_key' => ['nullable', 'string', 'max:500', 'required_with:license_email'],
], attributes: [
'portal_name' => 'Name des Portals', 'first_name' => 'Vorname', 'last_name' => 'Nachname',
'email' => 'E-Mail-Adresse', 'password' => 'Passwort',
'license_email' => 'Lizenz-E-Mail', 'license_key' => 'Lizenzschlüssel',
]);
@set_time_limit(300);
try {
Artisan::call('migrate', ['--force' => true]);
} catch (Throwable $e) {
return back()->withInput($request->except('password', 'password_confirmation', 'license_key'))
->withErrors(['portal_name' => 'Die Datenbank konnte nicht eingerichtet werden: '.$e->getMessage()]);
}
$admin = User::query()->updateOrCreate(['email' => strtolower($data['email'])], [
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'password' => $data['password'],
'is_admin' => true,
'is_active' => true,
]);
$settings->set('branding.portal_name', $data['portal_name']);
if (filled($data['license_email'] ?? null)) {
$license->setLicense($data['license_email'], $data['license_key']);
}
$license->deviceId();
file_put_contents(storage_path('.migrations-fingerprint'), $migrations->fingerprint());
Installation::markInstalled();
Audit::log('install.completed', ['portal_name' => $data['portal_name']], $admin->id);
return redirect('/login')->with('status', 'Die Einrichtung ist abgeschlossen. Sie können sich jetzt anmelden.');
}
private function pdoMessage(string $message): string
{
return match (true) {
str_contains($message, 'Access denied') => 'Benutzername oder Passwort sind falsch, oder der Benutzer hat keinen Zugriff auf diese Datenbank.',
str_contains($message, 'Unknown database') => 'Die Datenbank existiert nicht. Bitte zuerst beim Hoster anlegen.',
str_contains($message, 'getaddrinfo'), str_contains($message, 'Connection refused'), str_contains($message, 'timed out') => 'Der Datenbankserver ist nicht erreichbar. Bitte Server und Port prüfen.',
default => $message,
};
}
}

View file

@ -0,0 +1,23 @@
<?php
namespace App\Http\Middleware;
use App\Support\Installation;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Solange nicht eingerichtet, führt jede Seite zum Web-Installer.
*/
class RedirectToInstaller
{
public function handle(Request $request, Closure $next): Response
{
if (! Installation::isInstalled() && ! $request->is('install', 'install/*', 'up')) {
return redirect('/install');
}
return $next($request);
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace App\Http\Middleware;
use App\Support\BackgroundTasks;
use App\Support\Installation;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Pseudo-Cron: Läuft weder echter Cron noch Web-Cron, werden fällige
* Hintergrundaufgaben nach dem Ausliefern einer Seite erledigt – höchstens
* einmal pro Minute.
*/
class RunPseudoCron
{
public function __construct(private readonly BackgroundTasks $tasks) {}
public function handle(Request $request, Closure $next): Response
{
return $next($request);
}
public function terminate(Request $request, Response $response): void
{
if (app()->runningUnitTests() || ! Installation::isInstalled() || ! $this->tasks->pseudoCronDue()) {
return;
}
$this->tasks->run('pseudo');
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['user_id', 'type', 'payload', 'idempotency_key', 'status', 'attempts', 'next_attempt_at', 'reference', 'last_error'])]
class VendorFeedback extends Model
{
public const PENDING = 'pending';
public const SENT = 'sent';
public const DISCARDED = 'discarded';
public const TYPES = [
'bugreport' => 'Fehlerbericht',
'featurerequest' => 'Funktionswunsch',
];
protected $table = 'vendor_feedback';
protected function casts(): array
{
return [
'payload' => 'array',
'next_attempt_at' => 'datetime',
];
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}

View file

@ -4,7 +4,9 @@ namespace App\Providers;
use App\Models\User;
use App\Support\Avatars;
use App\Support\BackgroundTasks;
use App\Support\Branding;
use App\Support\Installation;
use App\Support\License\LicenseStore;
use App\Support\Navigation;
use App\Support\QuickLinks;
@ -21,12 +23,23 @@ class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
// Frisch hochgeladen: .env und Schlüssel anlegen; bis zur Einrichtung ohne Datenbank
// für Sitzungen, Cache und Queue auskommen (der Web-Installer braucht das).
if (! $this->app->runningUnitTests()) {
Installation::prepareEnvironment();
}
if (! Installation::isInstalled()) {
config(['session.driver' => 'file', 'cache.default' => 'file', 'queue.default' => 'sync']);
}
$this->app->singleton(Settings::class);
$this->app->singleton(Branding::class);
$this->app->singleton(Avatars::class);
$this->app->singleton(Navigation::class);
$this->app->singleton(QuickLinks::class);
$this->app->singleton(LicenseStore::class);
$this->app->singleton(BackgroundTasks::class);
$this->app->singleton(InstalledVersion::class);
$this->app->singleton(UpdateProgress::class);
$this->app->singleton(MaintenanceFlag::class);

View file

@ -3,7 +3,9 @@
namespace App\Providers\Filament;
use App\Filament\AvatarProviders\InitialsAvatarProvider;
use App\Filament\Pages\Feedback;
use App\Support\Branding;
use Filament\Actions\Action;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
@ -37,7 +39,14 @@ class AdminPanelProvider extends PanelProvider
->colors(fn () => [
'primary' => app(Branding::class)->palette(),
])
->navigationGroups(['Inhalte', 'Portal', 'System'])
->navigationGroups(['Inhalte', 'Portal', 'System', 'Hilfe'])
->databaseNotifications()
->userMenuItems([
Action::make('feedback')
->label('Rückmeldung geben')
->icon(Heroicon::OutlinedChatBubbleLeftEllipsis)
->url(fn () => Feedback::getUrl()),
])
->navigationItems([
NavigationItem::make('Zum Portal')
->url('/')

View file

@ -0,0 +1,80 @@
<?php
namespace App\Support;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Throwable;
/**
* Hintergrundaufgaben ohne Dauerprozess (Shared Hosting):
* 1. echter Cron: * * * * * php artisan schedule:run
* 2. Web-Cron: externer Dienst ruft /cron/{token} auf
* 3. Pseudo-Cron: nach Auslieferung einer Seite, wenn 1 und 2 fehlen (wie WP-Cron)
* Jeder Lauf hinterlässt ein Lebenszeichen, das „Systemzustand“ anzeigt.
*/
class BackgroundTasks
{
/** Ohne Lebenszeichen von Cron/Web-Cron springt der Pseudo-Cron ein. */
public const PSEUDO_CRON_AFTER_SECONDS = 300;
public function __construct(private readonly Settings $settings) {}
public function run(string $source): void
{
$lock = @fopen(storage_path('.background.lock'), 'c');
if ($lock === false || ! flock($lock, LOCK_EX | LOCK_NB)) {
return;
}
try {
@set_time_limit(55);
$this->heartbeat($source);
Artisan::call('schedule:run');
} catch (Throwable $e) {
Log::error('Hintergrundaufgaben fehlgeschlagen: '.$e->getMessage(), ['exception' => $e]);
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
public function heartbeat(string $source): void
{
$beats = $this->heartbeats();
$beats[$source] = now()->getTimestamp();
@file_put_contents(storage_path('.background-heartbeat'), json_encode($beats));
}
/**
* @return array<string, int> Quelle (cron, webcron, pseudo) => Zeitpunkt
*/
public function heartbeats(): array
{
$data = json_decode((string) @file_get_contents(storage_path('.background-heartbeat')), true);
return is_array($data) ? array_map('intval', $data) : [];
}
public function pseudoCronDue(): bool
{
$beats = $this->heartbeats();
$external = max($beats['cron'] ?? 0, $beats['webcron'] ?? 0);
return now()->getTimestamp() - $external > self::PSEUDO_CRON_AFTER_SECONDS
&& now()->getTimestamp() - ($beats['pseudo'] ?? 0) >= 60;
}
public function webCronToken(): string
{
$token = $this->settings->get('system.cron_token');
if (! is_string($token) || strlen($token) < 32) {
$token = bin2hex(random_bytes(20));
$this->settings->set('system.cron_token', $token);
}
return $token;
}
}

49
app/Support/EnvFile.php Normal file
View file

@ -0,0 +1,49 @@
<?php
namespace App\Support;
use App\Support\Update\AtomicFile;
/**
* Setzt Werte in einer .env-Datei (vorhandene Zeilen ersetzen, neue anhängen).
*/
class EnvFile
{
/**
* @param array<string, string|int|bool|null> $values
*/
public static function set(string $path, array $values): void
{
$content = is_file($path) ? (string) file_get_contents($path) : '';
foreach ($values as $key => $value) {
$line = $key.'='.self::format($value);
$pattern = '/^#?\s*'.preg_quote($key, '/').'=.*$/m';
$content = preg_match($pattern, $content)
? preg_replace($pattern, str_replace(['\\', '$'], ['\\\\', '\\$'], $line), $content, 1)
: rtrim($content, "\n")."\n".$line."\n";
}
AtomicFile::write($path, $content);
}
private static function format(string|int|bool|null $value): string
{
if ($value === null) {
return '';
}
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
$value = (string) $value;
if ($value === '' || preg_match('/^[A-Za-z0-9_.:\/@+=-]+$/', $value)) {
return $value;
}
return '"'.str_replace(['\\', '"', '$'], ['\\\\', '\\"', '\\$'], $value).'"';
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace App\Support\Feedback;
use App\Models\VendorFeedback;
use App\Support\Settings;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* Welche Meldewege für dieses Programm freigeschaltet sind – einmal täglich über
* GET /v1/software ermittelt. Ein 404 beim Senden blendet den Weg dauerhaft aus.
*/
class FeedbackChannels
{
public function __construct(private readonly Settings $settings) {}
/**
* @return array<string, string> Schlüssel => Bezeichnung
*/
public function available(): array
{
$enabled = Cache::remember('feedback.endpoints', now()->addDay(), fn () => $this->fetch());
$disabled = (array) $this->settings->get('feedback.disabled', []);
return collect(VendorFeedback::TYPES)
->only($enabled ?? array_keys(VendorFeedback::TYPES))
->except($disabled)
->all();
}
public function disable(string $type): void
{
$disabled = (array) $this->settings->get('feedback.disabled', []);
$this->settings->set('feedback.disabled', array_values(array_unique([...$disabled, $type])));
}
/**
* @return list<string>|null null = unbekannt (Server nicht erreichbar) – dann alle anbieten
*/
private function fetch(): ?array
{
try {
$software = Http::timeout(5)->acceptJson()->get(rtrim(config('updater.api_url'), '/').'/software')->json('software');
foreach ((array) $software as $entry) {
if (($entry['slug'] ?? null) === config('updater.software')) {
return array_values(array_filter((array) ($entry['endpoints'] ?? []), 'is_string'));
}
}
return [];
} catch (Throwable) {
return null;
}
}
}

View file

@ -0,0 +1,80 @@
<?php
namespace App\Support\Feedback;
use App\Support\License\ServerError;
use App\Support\License\VendorHttp;
/**
* Sendet Rückmeldungen an api.loheide.cloud (docs/specs/feedback.md).
* Lizenz-Kopfzeilen nur, wenn eine Lizenz hinterlegt ist; eine ungültige oder
* abgelaufene Lizenz verhindert das Senden nicht.
*/
class FeedbackClient
{
public function __construct(private readonly VendorHttp $http) {}
/**
* @param array<string, mixed> $payload
*/
public function send(string $type, array $payload, string $idempotencyKey, int $timeout = 10): FeedbackResult
{
try {
$response = VendorHttp::guard(fn () => $this->http->request($timeout, identifyDevice: false)
->withHeaders(['Idempotency-Key' => $idempotencyKey])
->post($this->url($type), $payload));
} catch (ServerError $e) {
return FeedbackResult::retry('Der Server ist nicht erreichbar.');
}
$data = $response->json() ?? [];
return match (true) {
$response->status() === 201 || ($response->successful() && isset($data['reference'])) => FeedbackResult::sent((string) ($data['reference'] ?? '')),
$response->status() === 404 => FeedbackResult::disabled(),
$response->status() === 422 => FeedbackResult::invalid($this->fieldErrors($data), $data['error'] ?? $data['message'] ?? null),
$response->status() === 429 => FeedbackResult::rateLimited($this->retryAfter($response->header('Retry-After'), $data)),
// 409: dieselbe Meldung wird gerade verarbeitet – kurz warten, dann erneut (kein Fehler).
$response->status() === 409 => FeedbackResult::retry('Wird bereits verarbeitet.', 30),
default => FeedbackResult::retry('Server antwortet mit HTTP '.$response->status().'.', $this->retryAfter($response->header('Retry-After'), $data)),
};
}
private function url(string $type): string
{
return rtrim(config('updater.api_url'), '/').'/software/'.config('updater.software').'/'.$type;
}
/**
* Unterstützt {"errors": {"feld": ["Grund"]}} und {"field": "feld", "error": "Grund"}.
*
* @param array<string, mixed> $data
* @return array<string, string>
*/
private function fieldErrors(array $data): array
{
$errors = [];
if (is_array($data['errors'] ?? null)) {
foreach ($data['errors'] as $field => $messages) {
$errors[(string) $field] = is_array($messages) ? (string) reset($messages) : (string) $messages;
}
}
if (is_string($data['field'] ?? null)) {
$errors[$data['field']] = (string) ($data['error'] ?? $data['message'] ?? 'Ungültige Eingabe.');
}
return $errors;
}
/**
* @param array<string, mixed> $data
*/
private function retryAfter(?string $header, array $data): ?int
{
$value = $data['retry_after'] ?? $header;
return is_numeric($value) ? (int) $value : null;
}
}

View file

@ -0,0 +1,137 @@
<?php
namespace App\Support\Feedback;
use App\Models\User;
use App\Models\VendorFeedback;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Log;
/**
* Warteschlange für Rückmeldungen: Die Meldung wird sofort gespeichert (samt
* Idempotency-Key) und dann zugestellt. Klappt das nicht, versucht es der
* Hintergrundlauf erneut – höchstens fünfmal, danach wird verworfen und die
* Person informiert.
*/
class FeedbackOutbox
{
public const MAX_ATTEMPTS = 5;
public function __construct(
private readonly FeedbackClient $client,
private readonly FeedbackChannels $channels,
) {}
/**
* Neue Meldung speichern und direkt einen ersten Zustellversuch machen.
*
* @param array<string, mixed> $payload
*/
public function submit(?User $user, string $type, array $payload): FeedbackResult
{
$feedback = VendorFeedback::query()->create([
'user_id' => $user?->id,
'type' => $type,
'payload' => $payload,
// Je Meldung EINMAL erzeugt und bei jedem Wiederholungsversuch mitgeschickt.
'idempotency_key' => bin2hex(random_bytes(16)),
'status' => VendorFeedback::PENDING,
'next_attempt_at' => now(),
]);
$result = $this->attempt($feedback, timeout: 8);
// Eingabe- und Mengenfehler klärt die Person im Formular – nicht die Warteschlange.
// Die Eingabe bleibt im Formular erhalten; eine neue Meldung bekommt einen neuen Schlüssel.
if (in_array($result->status, [FeedbackResult::INVALID, FeedbackResult::RATE_LIMITED, FeedbackResult::DISABLED], true)) {
$feedback->delete();
}
return $result;
}
/**
* Fällige Meldungen erneut senden (Hintergrundlauf). Nacheinander, damit das
* Gerätetoken zwischen den Anfragen nachgeführt wird.
*/
public function processDue(): int
{
$processed = 0;
VendorFeedback::query()
->where('status', VendorFeedback::PENDING)
->where('next_attempt_at', '<=', now())
->orderBy('id')
->limit(20)
->get()
->each(function (VendorFeedback $feedback) use (&$processed) {
$this->attempt($feedback);
$processed++;
});
return $processed;
}
private function attempt(VendorFeedback $feedback, int $timeout = 15): FeedbackResult
{
$result = $this->client->send($feedback->type, $feedback->payload, $feedback->idempotency_key, $timeout);
$attempts = $feedback->attempts + 1;
switch ($result->status) {
case FeedbackResult::SENT:
$feedback->update(['status' => VendorFeedback::SENT, 'attempts' => $attempts, 'reference' => $result->reference, 'last_error' => null]);
Log::info("Rückmeldung zugestellt: {$result->reference}");
break;
case FeedbackResult::DISABLED:
$this->channels->disable($feedback->type);
$this->discard($feedback, $attempts, 'Dieser Meldeweg ist für das Programm nicht freigeschaltet.');
break;
case FeedbackResult::INVALID:
case FeedbackResult::RATE_LIMITED:
if ($feedback->attempts > 0) {
// Nur im Hintergrund möglich (z. B. 429 bei Wiederholung): später erneut.
$this->reschedule($feedback, $attempts, $result->message ?? 'Später erneut versuchen.', $result->retryAfter);
}
break;
default:
$this->reschedule($feedback, $attempts, $result->message ?? 'Nicht zugestellt.', $result->retryAfter);
}
return $result;
}
private function reschedule(VendorFeedback $feedback, int $attempts, string $error, ?int $retryAfter): void
{
if ($attempts >= self::MAX_ATTEMPTS) {
$this->discard($feedback, $attempts, $error);
return;
}
// 1, 5, 15, 60 Minuten – oder so lange, wie der Server es verlangt.
$delay = $retryAfter ?? [60, 300, 900, 3600][min($attempts - 1, 3)];
$feedback->update([
'attempts' => $attempts,
'next_attempt_at' => now()->addSeconds(max(30, $delay)),
'last_error' => mb_substr($error, 0, 500),
]);
}
private function discard(VendorFeedback $feedback, int $attempts, string $error): void
{
$feedback->update(['status' => VendorFeedback::DISCARDED, 'attempts' => $attempts, 'last_error' => mb_substr($error, 0, 500)]);
Log::warning("Rückmeldung verworfen nach {$attempts} Versuchen: {$error}");
if ($feedback->user) {
Notification::make()
->danger()
->title('Rückmeldung konnte nicht zugestellt werden')
->body('„'.($feedback->payload['title'] ?? '').'“ wurde nach '.$attempts.' Versuchen verworfen. Bitte senden Sie die Meldung später erneut.')
->sendToDatabase($feedback->user);
}
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace App\Support\Feedback;
/**
* Ergebnis eines Zustellversuchs.
*/
final class FeedbackResult
{
public const SENT = 'sent';
public const INVALID = 'invalid';
public const RATE_LIMITED = 'rate_limited';
public const DISABLED = 'disabled';
public const RETRY = 'retry';
/**
* @param array<string, string> $errors Feld => Meldung (bei 422)
*/
private function __construct(
public readonly string $status,
public readonly ?string $reference = null,
public readonly array $errors = [],
public readonly ?int $retryAfter = null,
public readonly ?string $message = null,
) {}
public static function sent(string $reference): self
{
return new self(self::SENT, reference: $reference);
}
/**
* @param array<string, string> $errors
*/
public static function invalid(array $errors, ?string $message = null): self
{
return new self(self::INVALID, errors: $errors, message: $message);
}
public static function rateLimited(?int $retryAfter): self
{
return new self(self::RATE_LIMITED, retryAfter: $retryAfter);
}
public static function disabled(): self
{
return new self(self::DISABLED);
}
public static function retry(string $message, ?int $retryAfter = null): self
{
return new self(self::RETRY, retryAfter: $retryAfter, message: $message);
}
}

View file

@ -0,0 +1,64 @@
<?php
namespace App\Support\Feedback;
use App\Support\License\VendorHttp;
use App\Support\Update\Channels;
use App\Support\Update\InstalledVersion;
use App\Version;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
* Technische Angaben, die jede Meldung automatisch mitschickt – und die vor dem
* Absenden sichtbar sind. Keine personenbezogenen Daten, keine Dateipfade,
* keine Inhalte.
*/
class TechnicalInfo
{
public function __construct(
private readonly InstalledVersion $version,
private readonly Channels $channels,
) {}
/**
* @return array{app_version: string, current_sha: string|null, os: string, metadata: array<string, string|int>}
*/
public function collect(): array
{
return [
'app_version' => Version::VERSION,
'current_sha' => $this->version->current(),
'os' => VendorHttp::operatingSystem(),
'metadata' => array_filter([
'php' => PHP_VERSION,
'datenbank' => $this->database(),
'webserver' => $this->webserver(),
'update_kanal' => $this->channels->active(),
'cache' => (string) config('cache.default'),
'queue' => (string) config('queue.default'),
'sprache' => app()->getLocale(),
'opcache' => function_exists('opcache_get_status') && @opcache_get_status(false) ? 'an' : 'aus',
], fn ($value) => $value !== null && $value !== ''),
];
}
private function database(): ?string
{
try {
$version = (string) DB::selectOne('select version() as v')->v;
return (str_contains(strtolower($version), 'mariadb') ? 'MariaDB ' : 'MySQL ').preg_replace('/-.*$/', '', $version);
} catch (Throwable) {
return null;
}
}
private function webserver(): ?string
{
$software = (string) ($_SERVER['SERVER_SOFTWARE'] ?? '');
// Nur Produkt und Version, keine Modul-Liste.
return $software !== '' ? strtok($software, ' ') : PHP_SAPI;
}
}

View file

@ -2,14 +2,21 @@
namespace App\Support;
use Illuminate\Encryption\Encrypter;
/**
* Ob diese Installation eingerichtet ist. Der Web-Installer legt die Markierung
* storage/.installed an; lokale Entwicklungsumgebungen gelten immer als eingerichtet.
* Installationsstatus und Vorbereitung für den Web-Installer.
*/
class Installation
{
public static function isInstalled(): bool
{
$forced = config('inhaus.installed');
if ($forced !== null && $forced !== '') {
return filter_var($forced, FILTER_VALIDATE_BOOL);
}
return is_file(storage_path('.installed')) || app()->environment('local');
}
@ -17,4 +24,27 @@ class Installation
{
file_put_contents(storage_path('.installed'), date(DATE_ATOM));
}
/**
* Frisch hochgeladene Installation: .env aus der Vorlage anlegen und einen
* Anwendungsschlüssel erzeugen – ohne Schlüssel funktionieren weder Sitzungen
* noch Cookies, also auch der Installer nicht.
*/
public static function prepareEnvironment(): void
{
$env = app()->environmentFilePath();
if (! is_file($env) && is_file(base_path('.env.example')) && is_writable(base_path())) {
$key = 'base64:'.base64_encode(Encrypter::generateKey(config('app.cipher', 'AES-256-CBC')));
copy(base_path('.env.example'), $env);
EnvFile::set($env, [
'APP_KEY' => $key,
'APP_ENV' => 'production',
'APP_DEBUG' => 'false',
]);
config(['app.key' => $key, 'app.env' => 'production', 'app.debug' => false]);
}
}
}

View file

@ -4,6 +4,7 @@ namespace App\Support;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
use Throwable;
/**
* Systemweite Einstellungen als Schlüssel/Wert-Paare.
@ -47,10 +48,15 @@ class Settings
*/
public function all(): array
{
return $this->values ??= Cache::rememberForever(
self::CACHE_KEY,
fn () => Setting::query()->pluck('value', 'key')->all(),
);
try {
return $this->values ??= Cache::rememberForever(
self::CACHE_KEY,
fn () => Setting::query()->pluck('value', 'key')->all(),
);
} catch (Throwable) {
// Noch keine Datenbank (Web-Installer) oder vorübergehend nicht erreichbar.
return [];
}
}
public function flush(): void

262
app/Support/SiteHealth.php Normal file
View file

@ -0,0 +1,262 @@
<?php
namespace App\Support;
use App\Support\License\LicenseStore;
use App\Support\License\ServerError;
use App\Support\License\ServerMessages;
use App\Support\Update\MaintenanceFlag;
use App\Support\Update\Migrations;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
* Systemzustand: prüft Voraussetzungen und Betrieb. Wird im Admin-Bereich
* angezeigt und vom Web-Installer für die Systemprüfung genutzt.
*/
class SiteHealth
{
public const OK = 'ok';
public const WARNING = 'warning';
public const ERROR = 'error';
public const MIN_PHP = '8.3.0';
public const REQUIRED_EXTENSIONS = ['pdo_mysql', 'mbstring', 'openssl', 'intl', 'gd', 'zip', 'fileinfo', 'tokenizer', 'ctype', 'xml', 'dom'];
/**
* Voraussetzungen, die schon vor der Installation erfüllt sein müssen.
*
* @return list<array{label: string, status: string, message: string}>
*/
public function requirements(): array
{
$checks = [];
$checks[] = $this->check(
'PHP-Version',
version_compare(PHP_VERSION, self::MIN_PHP, '>='),
'PHP '.PHP_VERSION,
'Benötigt wird mindestens PHP '.self::MIN_PHP.'. Die Version lässt sich meist in der Verwaltung des Hosters umstellen.',
);
$missing = array_values(array_filter(self::REQUIRED_EXTENSIONS, fn (string $ext) => ! extension_loaded($ext)));
$checks[] = $this->check(
'PHP-Erweiterungen',
$missing === [],
'Alle vorhanden',
'Es fehlen: '.implode(', ', $missing).'. Bitte beim Hoster aktivieren.',
);
$checks[] = [
'label' => 'Ausgehende Verbindungen',
'status' => function_exists('curl_init') || ini_get('allow_url_fopen') ? self::OK : self::WARNING,
'message' => function_exists('curl_init') ? 'cURL verfügbar' : 'Weder cURL noch allow_url_fopen – Updates sind so nicht möglich.',
];
foreach (['storage' => storage_path(), 'bootstrap/cache' => base_path('bootstrap/cache'), 'public/uploads' => public_path('uploads')] as $label => $path) {
$checks[] = $this->check(
"Schreibrechte: {$label}",
$this->writable($path),
'Beschreibbar',
"Das Verzeichnis {$label} muss für den Webserver beschreibbar sein.",
);
}
$checks[] = [
'label' => 'Schreibrechte für Updates',
'status' => $this->writable(base_path('app')) && $this->writable(base_path('vendor')) && $this->writable(public_path('build')) ? self::OK : self::WARNING,
'message' => $this->writable(base_path('app'))
? 'Programmdateien sind beschreibbar – Aktualisierungen per Klick funktionieren.'
: 'Programmdateien sind nicht beschreibbar – Aktualisierungen per Klick sind so nicht möglich.',
];
return $checks;
}
/**
* Alle Prüfungen für die Seite „Systemzustand“.
*
* @return array<string, list<array{label: string, status: string, message: string}>>
*/
public function all(): array
{
return [
'Voraussetzungen' => $this->requirements(),
'Leistung und Grenzen' => $this->performance(),
'Betrieb' => $this->operations(),
'Sicherheit' => $this->security(),
];
}
/**
* @return list<array{label: string, status: string, message: string}>
*/
private function performance(): array
{
$opcache = function_exists('opcache_get_status') && @opcache_get_status(false);
$memory = self::bytes((string) ini_get('memory_limit'));
$upload = min(self::bytes((string) ini_get('upload_max_filesize')), self::bytes((string) ini_get('post_max_size')));
return [
[
'label' => 'OPcache',
'status' => $opcache ? self::OK : self::WARNING,
'message' => $opcache ? 'Aktiv' : 'Nicht aktiv – das Portal läuft deutlich langsamer. Bitte beim Hoster aktivieren.',
],
[
'label' => 'Arbeitsspeicher (memory_limit)',
'status' => $memory === -1 || $memory >= 128 * 1024 ** 2 ? self::OK : self::WARNING,
'message' => ini_get('memory_limit').($memory !== -1 && $memory < 128 * 1024 ** 2 ? ' – empfohlen sind mindestens 128M.' : ''),
],
[
'label' => 'Maximale Upload-Größe',
'status' => $upload === -1 || $upload >= 8 * 1024 ** 2 ? self::OK : self::WARNING,
'message' => ini_get('upload_max_filesize').' / '.ini_get('post_max_size').($upload !== -1 && $upload < 8 * 1024 ** 2 ? ' – für Fotos sind mindestens 8M empfohlen.' : ''),
],
$this->databaseCheck(),
];
}
/**
* @return list<array{label: string, status: string, message: string}>
*/
private function operations(): array
{
$beats = app(BackgroundTasks::class)->heartbeats();
$cron = max($beats['cron'] ?? 0, $beats['webcron'] ?? 0);
$pseudo = $beats['pseudo'] ?? 0;
$background = match (true) {
now()->getTimestamp() - $cron < 600 => ['status' => self::OK, 'message' => 'Läuft per '.(($beats['cron'] ?? 0) >= ($beats['webcron'] ?? 0) ? 'Cron' : 'Web-Cron').', zuletzt '.$this->ago($cron).'.'],
$pseudo > 0 => ['status' => self::WARNING, 'message' => 'Läuft nur beim Seitenaufruf (Pseudo-Cron), zuletzt '.$this->ago($pseudo).'. Zuverlässiger ist ein Cronjob.'],
default => ['status' => self::WARNING, 'message' => 'Noch kein Lauf erkannt. Bitte einen Cronjob einrichten (siehe unten).'],
};
try {
$pending = count(app(Migrations::class)->pending());
} catch (Throwable) {
$pending = null;
}
$license = app(LicenseStore::class);
$code = $license->lastStatus()['error_code'] ?? null;
return [
['label' => 'Hintergrundaufgaben', ...$background],
[
'label' => 'Datenbank-Migrationen',
'status' => $pending === 0 ? self::OK : ($pending === null ? self::ERROR : self::WARNING),
'message' => match (true) {
$pending === null => 'Status kann nicht gelesen werden.',
$pending === 0 => 'Alle angewendet.',
default => "{$pending} ausstehend – unter „Aktualisierung“ ausführen.",
},
],
[
'label' => 'Lizenz',
'status' => ! $license->hasLicense() || $code ? self::WARNING : self::OK,
'message' => match (true) {
! $license->hasLicense() => 'Keine Lizenz hinterlegt – Updates sind nicht möglich.',
$code !== null => ServerMessages::for(new ServerError($code, 0, $code)),
default => 'Hinterlegt.',
},
],
[
'label' => 'Wartungsmodus',
'status' => app(MaintenanceFlag::class)->isActive() ? self::WARNING : self::OK,
'message' => app(MaintenanceFlag::class)->isActive() ? 'Aktiv – es läuft gerade eine Aktualisierung.' : 'Aus',
],
];
}
/**
* @return list<array{label: string, status: string, message: string}>
*/
private function security(): array
{
$https = str_starts_with((string) config('app.url'), 'https://');
return [
[
'label' => 'Fehlerdetails (APP_DEBUG)',
'status' => match (true) {
config('app.debug') && app()->isProduction() => self::ERROR,
(bool) config('app.debug') => self::WARNING,
default => self::OK,
},
'message' => config('app.debug') ? 'Eingeschaltet – im Betrieb unbedingt ausschalten, sonst werden interne Details angezeigt.' : 'Ausgeschaltet',
],
[
'label' => 'Verschlüsselte Verbindung',
'status' => $https ? self::OK : self::WARNING,
'message' => $https ? 'Das Portal läuft über HTTPS.' : 'APP_URL beginnt nicht mit https:// – Anmeldedaten würden unverschlüsselt übertragen.',
],
[
'label' => 'Anwendungsschlüssel',
'status' => filled(config('app.key')) ? self::OK : self::ERROR,
'message' => filled(config('app.key')) ? 'Gesetzt' : 'APP_KEY fehlt.',
],
];
}
/**
* @return array{label: string, status: string, message: string}
*/
private function databaseCheck(): array
{
try {
$version = (string) DB::selectOne('select version() as v')->v;
$mariadb = str_contains(strtolower($version), 'mariadb');
$number = preg_replace('/^(\d+\.\d+\.\d+).*$/', '$1', $version);
$ok = version_compare($number, $mariadb ? '10.6.0' : '8.0.0', '>=');
return [
'label' => 'Datenbank',
'status' => $ok ? self::OK : self::WARNING,
'message' => ($mariadb ? 'MariaDB ' : 'MySQL ').$number.($ok ? '' : ' – unterstützt werden MySQL ab 8.0 und MariaDB ab 10.6.'),
];
} catch (Throwable) {
return ['label' => 'Datenbank', 'status' => self::ERROR, 'message' => 'Keine Verbindung.'];
}
}
/**
* @return array{label: string, status: string, message: string}
*/
private function check(string $label, bool $ok, string $okMessage, string $errorMessage): array
{
return ['label' => $label, 'status' => $ok ? self::OK : self::ERROR, 'message' => $ok ? $okMessage : $errorMessage];
}
private function writable(string $path): bool
{
return is_dir($path) ? is_writable($path) : is_writable(dirname($path));
}
private function ago(int $timestamp): string
{
return Carbon::createFromTimestamp($timestamp)->locale('de')->diffForHumans();
}
public static function bytes(string $value): int
{
$value = trim($value);
if ($value === '' || $value === '-1') {
return -1;
}
$number = (int) $value;
return match (strtolower(substr($value, -1))) {
'g' => $number * 1024 ** 3,
'm' => $number * 1024 ** 2,
'k' => $number * 1024,
default => $number,
};
}
}

View file

@ -2,7 +2,9 @@
use App\Http\Middleware\EnsureNotInMaintenance;
use App\Http\Middleware\HandleInertiaRequests;
use App\Http\Middleware\RedirectToInstaller;
use App\Http\Middleware\RunPendingMigrations;
use App\Http\Middleware\RunPseudoCron;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
@ -17,9 +19,11 @@ return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware): void {
$middleware->web(prepend: [
EnsureNotInMaintenance::class,
RedirectToInstaller::class,
], append: [
RunPendingMigrations::class,
HandleInertiaRequests::class,
RunPseudoCron::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {

9
config/inhaus.php Normal file
View file

@ -0,0 +1,9 @@
<?php
return [
// Erzwingt den Installationsstatus (Tests, Sonderfälle). Leer = automatisch:
// eingerichtet, wenn storage/.installed existiert oder APP_ENV=local ist.
'installed' => env('INHAUS_INSTALLED'),
];

View file

@ -0,0 +1,37 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Rückmeldungen an den Hersteller – zugleich Warteschlange für Meldungen, die
* (noch) nicht zugestellt werden konnten. Der Idempotency-Key liegt bewusst im
* selben Datensatz: Er muss bei jedem Wiederholungsversuch derselbe sein.
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('vendor_feedback', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
$table->string('type', 30);
$table->json('payload');
$table->char('idempotency_key', 32)->unique();
$table->string('status', 20)->default('pending');
$table->unsignedTinyInteger('attempts')->default(0);
$table->timestamp('next_attempt_at')->nullable();
$table->string('reference', 50)->nullable();
$table->string('last_error', 500)->nullable();
$table->timestamps();
$table->index(['status', 'next_attempt_at']);
});
}
public function down(): void
{
Schema::dropIfExists('vendor_feedback');
}
};

View file

@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('notifications', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('type');
$table->morphs('notifiable');
$table->text('data');
$table->timestamp('read_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('notifications');
}
};

View file

@ -19,6 +19,7 @@
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="INHAUS_INSTALLED" value="true"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="BROADCAST_CONNECTION" value="null"/>

View file

@ -0,0 +1,161 @@
<x-filament-panels::page>
<style>
.ih-form { display: grid; gap: 1.25rem; }
.ih-field { display: grid; gap: .375rem; }
.ih-label { font-size: .875rem; font-weight: 500; }
.ih-hint { font-size: .8125rem; color: rgb(107 114 128); }
.ih-error { font-size: .8125rem; color: rgb(220 38 38); }
.ih-grid2 { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); }
.ih-types { display: flex; flex-wrap: wrap; gap: .5rem 1.5rem; }
.ih-types label { display: inline-flex; align-items: center; gap: .5rem; font-size: .875rem; }
.ih-textarea { width: 100%; min-height: 9rem; border: 0; padding: .5rem .75rem; background: transparent; font-size: .875rem; resize: vertical; }
.ih-textarea:focus { outline: none; }
.ih-tech { font-size: .8125rem; }
.ih-tech summary { cursor: pointer; font-weight: 500; }
.ih-tech dl { display: grid; grid-template-columns: max-content 1fr; gap: .25rem 1rem; margin-top: .75rem; }
.ih-tech dt { color: rgb(107 114 128); }
.ih-tech dd { font-family: ui-monospace, monospace; word-break: break-all; }
.ih-privacy { font-size: .8125rem; line-height: 1.55; color: rgb(75 85 99); border-left: 3px solid rgb(209 213 219); padding: .25rem 0 .25rem 1rem; }
.ih-privacy ul { list-style: disc; padding-left: 1.25rem; margin: .5rem 0; }
.ih-privacy p { margin: .5rem 0; }
.ih-table { width: 100%; font-size: .875rem; border-collapse: collapse; }
.ih-table th { text-align: left; font-weight: 500; color: rgb(107 114 128); padding: .375rem .5rem .375rem 0; }
.ih-table td { padding: .5rem .5rem .5rem 0; border-top: 1px solid rgb(243 244 246); vertical-align: top; }
.dark .ih-hint, .dark .ih-privacy, .dark .ih-tech dt, .dark .ih-table th { color: rgb(156 163 175); }
.dark .ih-table td { border-color: rgb(55 65 81); }
</style>
@if ($lastReference)
<x-filament::callout color="success" icon="heroicon-o-check-circle" heading="Ihre Meldung ist eingegangen">
<x-slot name="description">Referenznummer für Rückfragen: <strong>{{ $lastReference }}</strong></x-slot>
</x-filament::callout>
@endif
@if ($notice)
<x-filament::callout color="warning" icon="heroicon-o-information-circle" :description="$notice" />
@endif
@if (count($types) === 0)
<x-filament::section>
<p class="ih-hint">Rückmeldungen an den Hersteller sind für dieses Programm derzeit nicht freigeschaltet.</p>
</x-filament::section>
@else
<x-filament::section heading="Neue Rückmeldung" description="Fehlerberichte und Wünsche gehen direkt an das Entwicklungsteam.">
<form wire:submit="submit" class="ih-form">
<div class="ih-field">
<span class="ih-label">Art der Meldung</span>
<div class="ih-types">
@foreach ($types as $key => $label)
<label><x-filament::input.radio wire:model.live="type" value="{{ $key }}" /> {{ $label }}</label>
@endforeach
</div>
</div>
<label class="ih-field">
<span class="ih-label">Betreff</span>
<x-filament::input.wrapper :valid="! $errors->has('subject')">
<x-filament::input type="text" wire:model="subject" maxlength="255" placeholder="Kurz und konkret, z. B. „Export bricht bei großen Listen ab“" />
</x-filament::input.wrapper>
@error('subject') <span class="ih-error">{{ $message }}</span> @enderror
</label>
<label class="ih-field">
<span class="ih-label">Beschreibung</span>
<x-filament::input.wrapper :valid="! $errors->has('body')">
<textarea class="ih-textarea" wire:model="body" placeholder="{{ $type === 'bugreport' ? 'Was haben Sie getan, was ist passiert, was hätten Sie erwartet?' : 'Was möchten Sie erreichen, und wie würde es Ihnen helfen?' }}"></textarea>
</x-filament::input.wrapper>
@error('body') <span class="ih-error">{{ $message }}</span> @enderror
</label>
@if ($type === 'bugreport')
<label class="ih-field" style="max-width: 16rem">
<span class="ih-label">Dringlichkeit</span>
<x-filament::input.wrapper>
<x-filament::input.select wire:model="severity">
<option value="low">Niedrig</option>
<option value="normal">Normal</option>
<option value="high">Hoch</option>
<option value="critical">Kritisch – Arbeit nicht möglich</option>
</x-filament::input.select>
</x-filament::input.wrapper>
</label>
@endif
<div class="ih-grid2">
<label class="ih-field">
<span class="ih-label">E-Mail für Rückfragen <span class="ih-hint">(freiwillig)</span></span>
<x-filament::input.wrapper :valid="! $errors->has('email')">
<x-filament::input type="email" wire:model="email" />
</x-filament::input.wrapper>
@error('email') <span class="ih-error">{{ $message }}</span> @enderror
</label>
<label class="ih-field">
<span class="ih-label">Name <span class="ih-hint">(freiwillig)</span></span>
<x-filament::input.wrapper>
<x-filament::input type="text" wire:model="name" />
</x-filament::input.wrapper>
</label>
</div>
<details class="ih-tech">
<summary>Diese technischen Angaben werden mitgesendet</summary>
<dl>
<dt>app_version</dt><dd>{{ $technical['app_version'] }}</dd>
<dt>current_sha</dt><dd>{{ $technical['current_sha'] ?? '–' }}</dd>
<dt>os</dt><dd>{{ $technical['os'] }}</dd>
@foreach ($technical['metadata'] as $key => $value)
<dt>metadata.{{ $key }}</dt><dd>{{ $value }}</dd>
@endforeach
</dl>
</details>
{{-- Datenschutzhinweis über dem Absendeknopf (docs/specs/feedback.md). Zeilen für nicht
gesendete Angaben sind gestrichen: Anhänge gibt es nicht, Lizenzdaten nur mit Lizenz. --}}
<div class="ih-privacy">
<p>Mit dem Absenden werden Daten an api.loheide.cloud übertragen. Übermittelt werden:</p>
<ul>
<li>Ihr Text: Betreff und Beschreibung</li>
<li>Name und E-Mail-Adresse, soweit Sie sie angeben – für Rückfragen</li>
@if ($hasLicense)
<li>Ihre Lizenzdaten, damit die Meldung Ihrem Konto zugeordnet werden kann</li>
@endif
<li>Programmversion, installierter Stand und Betriebssystem</li>
<li>technisch bedingt: Ihre IP-Adresse, Datum und Uhrzeit</li>
</ul>
<p>Bitte beachten: Was Sie in die Beschreibung schreiben, wird mit übertragen. Enthält es Namen, Adressen oder Vorgänge anderer Personen, entfernen Sie diese bitte vorher.</p>
<p>Zweck: Bearbeitung Ihrer Meldung und Rückfragen dazu. Das Senden ist freiwillig; es geschieht nur, wenn Sie es hier auslösen.</p>
</div>
<div>
<x-filament::button type="submit" icon="heroicon-o-paper-airplane">Absenden</x-filament::button>
</div>
</form>
</x-filament::section>
@endif
@if ($history->isNotEmpty())
<x-filament::section heading="Meine Rückmeldungen">
<table class="ih-table">
<thead><tr><th>Datum</th><th>Art</th><th>Betreff</th><th>Referenz / Status</th></tr></thead>
<tbody>
@foreach ($history as $item)
<tr>
<td>{{ $item->created_at->format('d.m.Y H:i') }}</td>
<td>{{ \App\Models\VendorFeedback::TYPES[$item->type] ?? $item->type }}</td>
<td>{{ $item->payload['title'] ?? '' }}</td>
<td>
@if ($item->status === 'sent')
<strong>{{ $item->reference }}</strong>
@elseif ($item->status === 'pending')
<x-filament::badge color="warning">wird gesendet ({{ $item->attempts }}. Versuch)</x-filament::badge>
@else
<x-filament::badge color="danger">nicht zugestellt</x-filament::badge>
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
</x-filament::section>
@endif
</x-filament-panels::page>

View file

@ -0,0 +1,39 @@
<x-filament-panels::page>
<style>
.ih-list { display: grid; }
.ih-item { display: grid; grid-template-columns: 1.5rem 14rem 1fr; gap: .75rem; padding: .625rem 0; border-top: 1px solid rgb(243 244 246); font-size: .875rem; align-items: start; }
.ih-item:first-child { border-top: 0; }
.ih-dot { width: .75rem; height: .75rem; border-radius: 999px; margin-top: .3rem; }
.ih-ok { background: rgb(22 163 74); }
.ih-warning { background: rgb(217 119 6); }
.ih-error { background: rgb(220 38 38); }
.ih-label { font-weight: 500; }
.ih-code { font-family: ui-monospace, monospace; font-size: .8125rem; word-break: break-all; padding: .5rem .75rem; border-radius: .5rem; background: rgb(243 244 246); }
.ih-hint { font-size: .875rem; color: rgb(107 114 128); margin: .5rem 0; }
.dark .ih-item { border-color: rgb(55 65 81); }
.dark .ih-code { background: rgb(31 41 55); }
.dark .ih-hint { color: rgb(156 163 175); }
@media (max-width: 640px) { .ih-item { grid-template-columns: 1.5rem 1fr; } .ih-item > :last-child { grid-column: 2; } }
</style>
@foreach ($groups as $heading => $checks)
<x-filament::section :heading="$heading">
<div class="ih-list">
@foreach ($checks as $check)
<div class="ih-item">
<span class="ih-dot ih-{{ $check['status'] }}" title="{{ ['ok' => 'in Ordnung', 'warning' => 'Hinweis', 'error' => 'Problem'][$check['status']] }}"></span>
<span class="ih-label">{{ $check['label'] }}</span>
<span>{{ $check['message'] }}</span>
</div>
@endforeach
</div>
</x-filament::section>
@endforeach
<x-filament::section heading="Hintergrundaufgaben einrichten" description="Für Rückmeldungen, geplante Inhalte und Aufräumarbeiten. Ohne Einrichtung laufen sie nur, wenn jemand das Portal aufruft.">
<p class="ih-hint">Am besten: ein Cronjob beim Hoster, der jede Minute läuft:</p>
<div class="ih-code">{{ $cronLine }}</div>
<p class="ih-hint">Ohne Cron-Zugang: diese Adresse jede Minute von einem Cron-Dienst aufrufen lassen (geheim halten):</p>
<div class="ih-code">{{ $webCronUrl }}</div>
</x-filament::section>
</x-filament-panels::page>

View file

@ -0,0 +1,55 @@
@extends('install.layout', ['step' => 3])
@section('content')
<h1>Portal und Administrator</h1>
<p class="lead">Mit diesem Konto verwalten Sie das Portal. Weitere Personen legen Sie später im Admin-Bereich an oder binden Ihren Identity Provider an.</p>
<form method="post" action="/install/konto">
@csrf
<label for="portal_name">Name des Portals</label>
<input id="portal_name" name="portal_name" value="{{ old('portal_name', 'Mitarbeiterportal') }}" required>
@error('portal_name') <div class="error">{{ $message }}</div> @enderror
<div class="row">
<div>
<label for="first_name">Vorname</label>
<input id="first_name" name="first_name" value="{{ old('first_name') }}" required autocomplete="given-name">
@error('first_name') <div class="error">{{ $message }}</div> @enderror
</div>
<div>
<label for="last_name">Nachname</label>
<input id="last_name" name="last_name" value="{{ old('last_name') }}" required autocomplete="family-name">
@error('last_name') <div class="error">{{ $message }}</div> @enderror
</div>
</div>
<label for="email">E-Mail-Adresse</label>
<input id="email" name="email" type="email" value="{{ old('email') }}" required autocomplete="username">
@error('email') <div class="error">{{ $message }}</div> @enderror
<div class="row">
<div>
<label for="password">Passwort</label>
<input id="password" name="password" type="password" required autocomplete="new-password">
</div>
<div>
<label for="password_confirmation">Wiederholen</label>
<input id="password_confirmation" name="password_confirmation" type="password" required autocomplete="new-password">
</div>
</div>
@error('password') <div class="error">{{ $message }}</div> @else <div class="hint">Mindestens 10 Zeichen, mit Buchstaben und Ziffern.</div> @enderror
<fieldset>
<legend>Lizenz (optional, für Updates)</legend>
<label for="license_email">Lizenz-E-Mail</label>
<input id="license_email" name="license_email" type="email" value="{{ old('license_email') }}" autocomplete="off">
@error('license_email') <div class="error">{{ $message }}</div> @enderror
<label for="license_key">Lizenzschlüssel</label>
<input id="license_key" name="license_key" type="password" autocomplete="off">
@error('license_key') <div class="error">{{ $message }}</div> @enderror
<div class="hint">Kann auch später unter „Aktualisierung“ hinterlegt werden.</div>
</fieldset>
<button type="submit">Einrichtung abschließen</button>
</form>
@endsection

View file

@ -0,0 +1,38 @@
@extends('install.layout', ['step' => 2])
@section('content')
<h1>Datenbank</h1>
<p class="lead">Die Zugangsdaten finden Sie in der Verwaltung Ihres Hosters. Die Datenbank muss dort bereits angelegt sein (MySQL ab 8.0 oder MariaDB ab 10.6).</p>
<form method="post" action="/install/datenbank">
@csrf
<div class="row3">
<div>
<label for="host">Server</label>
<input id="host" name="host" value="{{ old('host', $values['host']) }}" required>
</div>
<div>
<label for="port">Port</label>
<input id="port" name="port" type="number" value="{{ old('port', $values['port']) }}" required>
</div>
</div>
@error('host') <div class="error">{{ $message }}</div> @enderror
<label for="database">Name der Datenbank</label>
<input id="database" name="database" value="{{ old('database', $values['database']) }}" required>
@error('database') <div class="error">{{ $message }}</div> @enderror
<div class="row">
<div>
<label for="username">Benutzer</label>
<input id="username" name="username" value="{{ old('username', $values['username']) }}" required autocomplete="off">
</div>
<div>
<label for="password">Passwort</label>
<input id="password" name="password" type="password" autocomplete="off">
</div>
</div>
<button type="submit">Verbindung prüfen und speichern</button>
</form>
@endsection

View file

@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Einrichtung</title>
<style>
* { box-sizing: border-box; }
body { margin: 0; min-height: 100vh; background: #f4f5f7; color: #1a1d21; font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
main { max-width: 560px; margin: 0 auto; padding: 48px 16px; }
.card { background: #fff; border: 1px solid #e3e5e8; border-radius: 10px; padding: 32px; }
h1 { font-size: 22px; margin: 0 0 4px; }
.lead { color: #5f6670; margin: 0 0 24px; }
.steps { display: flex; gap: 8px; margin-bottom: 20px; font-size: 13px; color: #5f6670; }
.steps span { padding: 4px 10px; border-radius: 999px; background: #e9ebee; }
.steps .active { background: #0f4c5c; color: #fff; }
label { display: block; font-size: 13px; font-weight: 600; margin: 16px 0 6px; }
input { width: 100%; height: 40px; padding: 0 12px; border: 1px solid #d5d8dd; border-radius: 6px; font: inherit; }
input:focus { outline: 2px solid #8eb1bd; border-color: #31697a; }
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.row3 { display: grid; grid-template-columns: 3fr 1fr; gap: 12px; }
button { margin-top: 24px; height: 42px; padding: 0 20px; border: 0; border-radius: 6px; background: #0f4c5c; color: #fff; font: inherit; font-weight: 600; cursor: pointer; }
button:disabled { opacity: .5; cursor: not-allowed; }
.error { color: #c62828; font-size: 13px; margin-top: 6px; }
.hint { color: #5f6670; font-size: 13px; margin-top: 6px; }
.check { display: grid; grid-template-columns: 14px 1fr; gap: 12px; padding: 10px 0; border-top: 1px solid #eef0f2; }
.check:first-child { border-top: 0; }
.dot { width: 10px; height: 10px; border-radius: 50%; margin-top: 6px; }
.ok { background: #16a34a; } .warning { background: #d97706; } .error-dot { background: #dc2626; }
fieldset { border: 1px solid #e3e5e8; border-radius: 8px; padding: 4px 16px 16px; margin: 24px 0 0; }
legend { font-size: 13px; font-weight: 600; padding: 0 6px; }
@media (max-width: 480px) { .row, .row3 { grid-template-columns: 1fr; } .card { padding: 24px 18px; } }
</style>
</head>
<body>
<main>
<div class="steps">
<span @class(['active' => $step === 1])>1 Systemprüfung</span>
<span @class(['active' => $step === 2])>2 Datenbank</span>
<span @class(['active' => $step === 3])>3 Administrator</span>
</div>
<div class="card">
@yield('content')
</div>
</main>
</body>
</html>

View file

@ -0,0 +1,21 @@
@extends('install.layout', ['step' => 1])
@section('content')
<h1>Willkommen</h1>
<p class="lead">In drei Schritten ist Ihr Mitarbeiterportal eingerichtet. Zuerst prüfen wir, ob der Server alles Nötige mitbringt.</p>
@foreach ($checks as $check)
<div class="check">
<span @class(['dot', 'ok' => $check['status'] === 'ok', 'warning' => $check['status'] === 'warning', 'error-dot' => $check['status'] === 'error'])></span>
<div><strong>{{ $check['label'] }}</strong><br><span class="hint">{{ $check['message'] }}</span></div>
</div>
@endforeach
@unless ($envWritable)
<p class="error">Die Konfigurationsdatei .env fehlt oder ist nicht beschreibbar. Bitte Schreibrechte für das Installationsverzeichnis vergeben.</p>
@endunless
<form action="/install/datenbank" method="get">
<button type="submit" @disabled(! $canContinue)>Weiter zur Datenbank</button>
</form>
@endsection

View file

@ -1,8 +1,26 @@
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use App\Support\BackgroundTasks;
use App\Support\Feedback\FeedbackOutbox;
use Illuminate\Support\Facades\Schedule;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');
/*
| Geplante Aufgaben. Ausgelöst per Cron, Web-Cron oder Pseudo-Cron (App\Support\BackgroundTasks).
*/
// Lebenszeichen des echten Crons. Web-Cron und Pseudo-Cron vermerken sich selbst.
Schedule::call(fn () => app(BackgroundTasks::class)->heartbeat('cron'))
->everyMinute()
->name('heartbeat')
->when(fn () => app()->runningInConsole());
Schedule::call(fn () => app(FeedbackOutbox::class)->processDue())
->everyMinute()
->name('feedback-outbox')
->withoutOverlapping(10);
// Aufträge der Datenbank-Queue in kurzen Häppchen abarbeiten (kein Dauerprozess nötig).
Schedule::command('queue:work --stop-when-empty --max-time=40 --tries=3')
->everyMinute()
->name('queue')
->withoutOverlapping(5);

View file

@ -1,13 +1,27 @@
<?php
use App\Http\Controllers\Admin\UpdateController;
use App\Http\Controllers\CronController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\EventController;
use App\Http\Controllers\InstallController;
use App\Http\Controllers\NewsController;
use App\Http\Controllers\PeopleController;
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
// Web-Installer – nur solange die Installation nicht eingerichtet ist.
Route::prefix('install')->middleware('throttle:30,1')->group(function () {
Route::get('/', [InstallController::class, 'requirements']);
Route::get('/datenbank', [InstallController::class, 'database']);
Route::post('/datenbank', [InstallController::class, 'saveDatabase']);
Route::get('/konto', [InstallController::class, 'account']);
Route::post('/konto', [InstallController::class, 'saveAccount']);
});
// Web-Cron für Hoster ohne Cron (siehe App\Support\BackgroundTasks).
Route::get('/cron/{token}', CronController::class)->middleware('throttle:10,1')->name('cron');
// Login, Logout und Passwort-Reset stellt Laravel Fortify bereit (FortifyServiceProvider).
Route::middleware('auth')->group(function () {

0
storage/.background.lock Normal file
View file

View file

@ -0,0 +1 @@
e880d7878d8f731b6539839a9721d2bff91c425b

View file

@ -0,0 +1,53 @@
<?php
namespace Tests\Feature;
use App\Support\BackgroundTasks;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class BackgroundTasksTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
@unlink(storage_path('.background-heartbeat'));
}
protected function tearDown(): void
{
@unlink(storage_path('.background-heartbeat'));
parent::tearDown();
}
public function test_web_cron_requires_the_secret_token(): void
{
$token = app(BackgroundTasks::class)->webCronToken();
$this->assertSame(40, strlen($token));
$this->get('/cron/falsch')->assertNotFound();
$this->get("/cron/{$token}")->assertNoContent();
$this->assertArrayHasKey('webcron', app(BackgroundTasks::class)->heartbeats());
}
public function test_pseudo_cron_only_steps_in_without_external_cron(): void
{
$tasks = app(BackgroundTasks::class);
$this->assertTrue($tasks->pseudoCronDue());
$tasks->heartbeat('cron');
$this->assertFalse($tasks->pseudoCronDue());
$this->travel(BackgroundTasks::PSEUDO_CRON_AFTER_SECONDS + 5)->seconds();
$this->assertTrue($tasks->pseudoCronDue());
$tasks->heartbeat('pseudo');
$this->assertFalse($tasks->pseudoCronDue(), 'Höchstens einmal pro Minute.');
}
}

View file

@ -0,0 +1,274 @@
<?php
namespace Tests\Feature\Feedback;
use App\Filament\Pages\Feedback;
use App\Models\User;
use App\Models\VendorFeedback;
use App\Support\Feedback\FeedbackChannels;
use App\Support\Feedback\FeedbackOutbox;
use App\Support\Feedback\FeedbackResult;
use App\Support\License\LicenseStore;
use App\Support\Update\Filesystem;
use App\Support\Update\InstalledVersion;
use App\Version;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Livewire\Livewire;
use Tests\TestCase;
class FeedbackTest extends TestCase
{
use RefreshDatabase;
private const URL = 'https://api.loheide.cloud/v1/software/mitarbeiterportal/bugreport';
private string $dir;
protected function setUp(): void
{
parent::setUp();
$this->dir = sys_get_temp_dir().'/inhaus-fb-'.bin2hex(random_bytes(4));
mkdir($this->dir);
$this->app->instance(LicenseStore::class, new LicenseStore($this->dir.'/license.json'));
$this->app->instance(InstalledVersion::class, new InstalledVersion($this->dir.'/.version'));
app(InstalledVersion::class)->save(str_repeat('9', 40));
Cache::put('feedback.endpoints', ['bugreport', 'featurerequest', 'telemetry'], 60);
}
protected function tearDown(): void
{
Filesystem::deleteDirectory($this->dir);
parent::tearDown();
}
/**
* @return array<string, mixed>
*/
private function payload(): array
{
return ['title' => 'Export bricht ab', 'body' => 'Ab etwa 5000 Zeilen passiert nichts mehr.', 'severity' => 'high'];
}
public function test_request_body_and_headers_with_license(): void
{
app(LicenseStore::class)->setLicense('lizenz@firma.de', 'KEY-1');
Http::fake([self::URL => Http::response(['ok' => true, 'reference' => 'BUG-8F3K2Q', 'id' => 'x'], 201)]);
$user = User::factory()->admin()->create();
$this->actingAs($user);
Livewire::test(Feedback::class)
->set('type', 'bugreport')
->set('subject', 'Export bricht ab')
->set('body', 'Ab etwa 5000 Zeilen passiert nichts mehr.')
->set('severity', 'high')
->set('email', 'rueckfrage@firma.de')
->call('submit')
->assertHasNoErrors()
->assertSet('lastReference', 'BUG-8F3K2Q')
->assertSet('subject', '')
->assertSee('BUG-8F3K2Q');
Http::assertSent(function (Request $request) {
$data = $request->data();
return $request->url() === self::URL
&& $request->method() === 'POST'
&& $request->hasHeader('X-License-Email', 'lizenz@firma.de')
&& $request->hasHeader('Authorization', 'Bearer KEY-1')
&& strlen($request->header('Idempotency-Key')[0]) === 32
&& $data['title'] === 'Export bricht ab'
&& $data['email'] === 'rueckfrage@firma.de'
&& $data['severity'] === 'high'
&& $data['app_version'] === Version::VERSION
&& $data['current_sha'] === str_repeat('9', 40)
&& $data['os'] !== ''
&& isset($data['metadata']['php'])
&& ! isset($data['name']);
});
$feedback = VendorFeedback::query()->sole();
$this->assertSame('sent', $feedback->status);
$this->assertSame('BUG-8F3K2Q', $feedback->reference);
}
public function test_no_license_headers_without_license(): void
{
Http::fake([self::URL => Http::response(['ok' => true, 'reference' => 'BUG-1'], 201)]);
app(FeedbackOutbox::class)->submit(null, 'bugreport', $this->payload());
Http::assertSent(fn (Request $request) => ! $request->hasHeader('X-License-Email')
&& ! $request->hasHeader('Authorization')
&& ! $request->hasHeader('X-Device-Id'));
}
public function test_expired_license_does_not_prevent_sending(): void
{
app(LicenseStore::class)->setLicense('lizenz@firma.de', 'ABGELAUFEN');
app(LicenseStore::class)->rememberStatus(null, 'license_expired');
Http::fake([self::URL => Http::response(['ok' => true, 'reference' => 'BUG-2'], 201)]);
$result = app(FeedbackOutbox::class)->submit(null, 'bugreport', $this->payload());
$this->assertSame(FeedbackResult::SENT, $result->status);
Http::assertSentCount(1);
}
public function test_422_shows_error_on_field_and_keeps_input(): void
{
Http::fake([self::URL => Http::response(['code' => 'validation_failed', 'errors' => ['title' => ['Der Betreff ist zu lang.']]], 422)]);
$this->actingAs(User::factory()->admin()->create());
Livewire::test(Feedback::class)
->set('type', 'bugreport')
->set('subject', 'Betreff')
->set('body', 'Eine ausreichend lange Beschreibung.')
->call('submit')
->assertHasErrors(['subject'])
->assertSet('subject', 'Betreff')
->assertSet('body', 'Eine ausreichend lange Beschreibung.');
$this->assertSame(0, VendorFeedback::query()->count());
}
public function test_429_names_the_waiting_time_and_keeps_input(): void
{
Http::fake([self::URL => Http::response(['code' => 'rate_limited'], 429, ['Retry-After' => '600'])]);
$this->actingAs(User::factory()->admin()->create());
Livewire::test(Feedback::class)
->set('type', 'bugreport')
->set('subject', 'Betreff')
->set('body', 'Eine ausreichend lange Beschreibung.')
->call('submit')
->assertSet('notice', fn (string $notice) => str_contains($notice, 'in etwa 10 Minute(n)'))
->assertSet('body', 'Eine ausreichend lange Beschreibung.');
Http::assertSentCount(1);
$this->assertSame(0, VendorFeedback::query()->count());
}
public function test_404_hides_the_channel_permanently(): void
{
Http::fake([self::URL => Http::response(['code' => 'not_found'], 404)]);
$this->actingAs(User::factory()->admin()->create());
Livewire::test(Feedback::class)
->set('type', 'bugreport')
->set('subject', 'Betreff')
->set('body', 'Eine ausreichend lange Beschreibung.')
->call('submit')
->assertSet('type', 'featurerequest')
->assertSet('body', 'Eine ausreichend lange Beschreibung.');
$this->assertSame(['featurerequest' => 'Funktionswunsch'], app(FeedbackChannels::class)->available());
}
public function test_only_enabled_channels_are_offered(): void
{
Cache::put('feedback.endpoints', ['featurerequest', 'telemetry'], 60);
$this->assertSame(['featurerequest' => 'Funktionswunsch'], app(FeedbackChannels::class)->available());
}
public function test_channels_are_read_from_software_list(): void
{
Cache::forget('feedback.endpoints');
Http::fake(['api.loheide.cloud/v1/software' => Http::response(['software' => [
['slug' => 'andere', 'endpoints' => ['bugreport']],
['slug' => 'mitarbeiterportal', 'endpoints' => ['bugreport', 'telemetry']],
]])]);
$this->assertSame(['bugreport' => 'Fehlerbericht'], app(FeedbackChannels::class)->available());
}
public function test_503_queues_and_retries_with_same_idempotency_key(): void
{
Http::fakeSequence(self::URL)
->push(['code' => 'maintenance'], 503)
->push(['code' => 'maintenance'], 503)
->push(['ok' => true, 'reference' => 'BUG-SPAET'], 201);
$result = app(FeedbackOutbox::class)->submit(null, 'bugreport', $this->payload());
$this->assertSame(FeedbackResult::RETRY, $result->status);
$feedback = VendorFeedback::query()->sole();
$this->assertSame('pending', $feedback->status);
$this->assertSame(1, $feedback->attempts);
// Noch nicht fällig.
$this->assertSame(0, app(FeedbackOutbox::class)->processDue());
$this->travel(2)->minutes();
app(FeedbackOutbox::class)->processDue();
$this->travel(10)->minutes();
app(FeedbackOutbox::class)->processDue();
$feedback->refresh();
$this->assertSame('sent', $feedback->status);
$this->assertSame('BUG-SPAET', $feedback->reference);
$keys = collect(Http::recorded())->map(fn ($pair) => $pair[0]->header('Idempotency-Key')[0])->unique();
$this->assertCount(1, $keys, 'Wiederholungen müssen denselben Idempotency-Key senden.');
}
public function test_gives_up_after_five_attempts_and_informs_the_user(): void
{
Http::fake([self::URL => Http::response('', 503)]);
$user = User::factory()->admin()->create();
app(FeedbackOutbox::class)->submit($user, 'bugreport', $this->payload());
for ($i = 0; $i < 6; $i++) {
$this->travel(2)->hours();
app(FeedbackOutbox::class)->processDue();
}
$feedback = VendorFeedback::query()->sole();
$this->assertSame('discarded', $feedback->status);
$this->assertSame(5, $feedback->attempts);
Http::assertSentCount(5);
$this->assertSame(1, $user->notifications()->count());
}
public function test_network_failure_is_queued(): void
{
Http::fake([self::URL => fn () => throw new ConnectionException('offline')]);
$result = app(FeedbackOutbox::class)->submit(null, 'bugreport', $this->payload());
$this->assertSame(FeedbackResult::RETRY, $result->status);
$this->assertSame('pending', VendorFeedback::query()->sole()->status);
}
public function test_409_is_not_shown_as_error_but_retried(): void
{
Http::fake([self::URL => Http::response(['code' => 'in_progress'], 409)]);
$result = app(FeedbackOutbox::class)->submit(null, 'bugreport', $this->payload());
$this->assertSame(FeedbackResult::RETRY, $result->status);
$this->assertTrue(VendorFeedback::query()->sole()->next_attempt_at->isFuture());
}
public function test_page_shows_technical_info_and_privacy_notice_and_is_admin_only(): void
{
$this->actingAs(User::factory()->create())->get('/admin/rueckmeldung')->assertForbidden();
$this->actingAs(User::factory()->admin()->create())
->get('/admin/rueckmeldung')
->assertOk()
->assertSee('Diese technischen Angaben werden mitgesendet')
->assertSee(Version::VERSION)
->assertSee(str_repeat('9', 40))
->assertSee('Mit dem Absenden werden Daten an api.loheide.cloud übertragen.')
->assertDontSee('die von Ihnen angehängten Dateien')
->assertDontSee('Ihre Lizenzdaten, damit die Meldung');
}
}

View file

@ -0,0 +1,115 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Support\Installation;
use App\Support\License\LicenseStore;
use App\Support\Settings;
use App\Support\Update\Filesystem;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class InstallerTest extends TestCase
{
use RefreshDatabase;
private string $dir;
protected function setUp(): void
{
parent::setUp();
$this->dir = sys_get_temp_dir().'/inhaus-inst-'.bin2hex(random_bytes(4));
mkdir($this->dir);
copy(base_path('.env.example'), $this->dir.'/.env');
$this->app->useEnvironmentPath($this->dir);
$this->app->instance(LicenseStore::class, new LicenseStore($this->dir.'/license.json'));
config(['inhaus.installed' => false]);
}
protected function tearDown(): void
{
@unlink(storage_path('.installed'));
Filesystem::deleteDirectory($this->dir);
parent::tearDown();
}
public function test_every_page_leads_to_the_installer(): void
{
$this->get('/')->assertRedirect('/install');
$this->get('/login')->assertRedirect('/install');
$this->get('/install')->assertOk()->assertSee('Systemprüfung')->assertSee('PHP-Version');
}
public function test_wrong_database_credentials_are_explained(): void
{
$this->post('/install/datenbank', [
'host' => config('database.connections.mysql.host'),
'port' => config('database.connections.mysql.port'),
'database' => config('database.connections.mysql.database'),
'username' => 'gibtesnicht',
'password' => 'falsch',
])->assertSessionHasErrors(['host' => 'Verbindung fehlgeschlagen: Benutzername oder Passwort sind falsch, oder der Benutzer hat keinen Zugriff auf diese Datenbank.']);
}
public function test_database_settings_are_written_to_env(): void
{
$this->post('/install/datenbank', [
'host' => config('database.connections.mysql.host'),
'port' => config('database.connections.mysql.port'),
'database' => config('database.connections.mysql.database'),
'username' => config('database.connections.mysql.username'),
'password' => config('database.connections.mysql.password'),
])->assertRedirect('/install/konto');
$env = file_get_contents($this->dir.'/.env');
$this->assertStringContainsString('DB_DATABASE='.config('database.connections.mysql.database'), $env);
$this->assertStringContainsString('DB_USERNAME='.config('database.connections.mysql.username'), $env);
$this->assertStringContainsString('APP_URL='.url('/'), $env);
}
public function test_account_step_completes_the_installation(): void
{
$this->post('/install/konto', [
'portal_name' => 'Caritas-Netz',
'first_name' => 'Ada',
'last_name' => 'Admin',
'email' => 'Ada@Example.com',
'password' => 'SicheresPasswort1',
'password_confirmation' => 'SicheresPasswort1',
'license_email' => 'lizenz@example.com',
'license_key' => 'KEY-123',
])->assertRedirect('/login');
$admin = User::query()->where('email', 'ada@example.com')->sole();
$this->assertTrue($admin->is_admin);
$this->assertSame('Ada Admin', $admin->name);
$this->assertSame('Caritas-Netz', app(Settings::class)->get('branding.portal_name'));
$this->assertSame('KEY-123', app(LicenseStore::class)->key());
$this->assertFileExists(storage_path('.installed'));
config(['inhaus.installed' => null]);
$this->assertTrue(Installation::isInstalled());
$this->get('/install')->assertNotFound();
}
public function test_weak_admin_password_is_rejected(): void
{
$this->post('/install/konto', [
'portal_name' => 'Portal', 'first_name' => 'A', 'last_name' => 'B', 'email' => 'a@example.com',
'password' => 'kurz', 'password_confirmation' => 'kurz',
])->assertSessionHasErrors('password');
$this->assertFileDoesNotExist(storage_path('.installed'));
}
public function test_installer_is_gone_once_installed(): void
{
config(['inhaus.installed' => true]);
$this->get('/install')->assertNotFound();
$this->post('/install/konto', [])->assertNotFound();
}
}

View file

@ -0,0 +1,42 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Support\SiteHealth;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class SiteHealthTest extends TestCase
{
use RefreshDatabase;
public function test_requirements_are_met_in_this_environment(): void
{
$requirements = app(SiteHealth::class)->requirements();
foreach ($requirements as $check) {
$this->assertNotSame(SiteHealth::ERROR, $check['status'], $check['label'].': '.$check['message']);
}
}
public function test_page_shows_checks_and_cron_setup(): void
{
$this->actingAs(User::factory()->create())->get('/admin/systemzustand')->assertForbidden();
$this->actingAs(User::factory()->admin()->create())
->get('/admin/systemzustand')
->assertOk()
->assertSee('PHP-Version')
->assertSee('Hintergrundaufgaben')
->assertSee('php artisan schedule:run')
->assertSee('/cron/');
}
public function test_byte_values_are_parsed(): void
{
$this->assertSame(128 * 1024 ** 2, SiteHealth::bytes('128M'));
$this->assertSame(2 * 1024 ** 3, SiteHealth::bytes('2G'));
$this->assertSame(-1, SiteHealth::bytes('-1'));
}
}