Files
deskhub/DeskHub-Webseite/tests/staff_activity.php
T
2026-10-21 16:44:52 +00:00

205 lines
15 KiB
PHP

<?php
declare(strict_types=1);
/**
* Prüft den automatischen Offline-Status (includes/staff_activity.php) und die Statusänderung durch Admins gegen eine echte
* Installation auf einem Test-Webserver: Inaktive Mitarbeiter gehen offline und kommen bei Aktivität zurück, Hintergrund-Abrufe
* zählen nicht als Aktivität, manuelle Status bleiben, Admins dürfen fremde Status ändern (Mitarbeiter nicht), Zeit einstellbar.
*/
if (!extension_loaded('pdo_sqlite') || !function_exists('curl_init')) { echo "Aktivitäts-Test übersprungen: pdo_sqlite oder curl fehlt.\n"; exit(0); }
date_default_timezone_set('Europe/Berlin'); // wie in der Test-Installation
$root = dirname(__DIR__);
$work = sys_get_temp_dir() . '/deskhub-activity-' . bin2hex(random_bytes(4));
$tmp = $work . '/inst';
mkdir($tmp, 0755, true);
$webPort = random_int(33000, 33499);
$skip = '#^(config/config\.php|database/[^/]+\.sqlite[^/]*|backups|uploads|tests|plugins/[^/]+|\.git)(/|$)#';
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $f) {
$rel = str_replace(chr(92), '/', substr($f->getPathname(), strlen($root) + 1));
if (preg_match($skip, $rel) && !preg_match('#^(backups|uploads|plugins)/(\.htaccess|README\.md)$#', $rel)) continue;
if ($f->isDir()) { @mkdir($tmp . '/' . $rel, 0755, true); continue; }
@mkdir(dirname($tmp . '/' . $rel), 0755, true);
copy($f->getPathname(), $tmp . '/' . $rel);
}
@mkdir($tmp . '/uploads');
@mkdir($tmp . '/config');
file_put_contents($tmp . '/config/config.php', '<?php return ' . var_export([
'app_key' => bin2hex(random_bytes(32)),
'db' => ['driver' => 'sqlite', 'sqlite_path' => $tmp . '/database/deskhub.sqlite'],
'site' => ['name' => 'Test', 'url' => 'http://127.0.0.1', 'admin_email' => 'a@test.de', 'timezone' => 'Europe/Berlin'],
'uploads' => ['max_size_bytes' => 10485760, 'allowed_extensions' => ['png'], 'path' => $tmp . '/uploads'],
], true) . ';');
putenv('DESKHUB_CONFIG_JSON');
putenv('DESKHUB_SQLITE_PATH');
putenv('DESKHUB_TESTING');
putenv('DESKHUB_API_ALLOW_INSECURE=1');
require_once $root . '/database/sqlite_schema.php';
require_once $root . '/database/migrate.php';
$db = new PDO('sqlite:' . $tmp . '/database/deskhub.sqlite');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->exec('PRAGMA foreign_keys = ON');
$db->exec(convert_schema_to_sqlite((string) file_get_contents($root . '/database/schema.sql')));
$mig = run_migrations($db, true);
$now = date('Y-m-d H:i:s');
$dept = (int) $db->query('SELECT id FROM departments ORDER BY id LIMIT 1')->fetchColumn();
$db->exec('DELETE FROM staff');
$ins = $db->prepare('INSERT INTO staff (name, email, password_hash, role, department_id, is_active, created_at) VALUES (?,?,?,?,?,1,?)');
$ids = [];
foreach ([['Chef', 'chef@test.de', 'admin'], ['Agent', 'agent@test.de', 'agent'], ['Andere', 'andere@test.de', 'agent']] as [$n, $e, $r]) {
$ins->execute([$n, $e, password_hash('Sehr-Sicher-1234', PASSWORD_DEFAULT), $r, $dept, $now]);
$ids[$n] = (int) $db->lastInsertId();
}
$db = null;
$failures = [];
$total = 0;
$check = function (bool $ok, string $what) use (&$failures, &$total): void { $total++; if (!$ok) $failures[] = $what; };
$webProc = proc_open([PHP_BINARY, '-S', "127.0.0.1:$webPort", '-t', $tmp], [['pipe', 'r'], ['file', $work . '/web.out', 'w'], ['file', $work . '/web.out', 'a']], $wp, $tmp);
try {
for ($i = 0; $i < 50; $i++) { if (@fsockopen('127.0.0.1', $webPort)) break; usleep(100000); }
$pdo = function () use ($tmp): PDO {
$p = new PDO('sqlite:' . $tmp . '/database/deskhub.sqlite');
$p->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$p->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $p;
};
$call = function (string $method, string $path, ?array $json = null, ?string $bearer = null, array $form = [], string $jar = '', array $extra = []) use ($webPort): array {
$ch = curl_init("http://127.0.0.1:$webPort$path");
$h = array_merge($json !== null ? ['Content-Type: application/json'] : [], $extra);
if ($bearer) $h[] = 'Authorization: Bearer ' . $bearer;
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 60, CURLOPT_HTTPHEADER => $h]);
if ($jar !== '') { curl_setopt($ch, CURLOPT_COOKIEJAR, $jar); curl_setopt($ch, CURLOPT_COOKIEFILE, $jar); }
if ($method === 'POST') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json !== null ? json_encode($json) : http_build_query($form)); }
$b = (string) curl_exec($ch);
$s = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
return [$s, json_decode($b, true) ?? $b];
};
$row = fn(string $name) => $pdo()->query('SELECT s.last_active_at, sa.status, sa.auto_offline, sa.prev_status, sa.note FROM staff s LEFT JOIN staff_availability sa ON sa.staff_id = s.id WHERE s.id = ' . (int) $ids[$name])->fetch();
$setActive = function (string $name, int $minutesAgo) use ($pdo, $ids): void {
$pdo()->prepare('UPDATE staff SET last_active_at = ? WHERE id = ?')->execute([date('Y-m-d H:i:s', time() - $minutesAgo * 60), $ids[$name]]);
};
$check(!array_filter($mig['errors'] ?? [], fn($e) => str_contains($e, 'php_0042')), 'Migration 0042 läuft ohne Fehler');
[, $a] = $call('POST', '/api/staff/v1/login.php', ['email' => 'agent@test.de', 'password' => 'Sehr-Sicher-1234', 'deviceName' => 'T']);
[, $c] = $call('POST', '/api/staff/v1/login.php', ['email' => 'chef@test.de', 'password' => 'Sehr-Sicher-1234', 'deviceName' => 'T']);
[, $o] = $call('POST', '/api/staff/v1/login.php', ['email' => 'andere@test.de', 'password' => 'Sehr-Sicher-1234', 'deviceName' => 'T']);
[$agent, $chef, $other] = [(string) ($a['token'] ?? ''), (string) ($c['token'] ?? ''), (string) ($o['token'] ?? '')];
$check($agent !== '' && $chef !== '' && $other !== '', 'Anmeldung über die Mitarbeiter-API');
// Status setzen zählt als Aktivität; Admin darf fremde Status ändern, Mitarbeiter nicht
[$s] = $call('POST', '/api/staff/v1/availability.php', ['status' => 'available'], $agent);
$check($s === 200 && $row('Agent')['status'] === 'available' && $row('Agent')['last_active_at'] !== null, 'Eigenen Status setzen funktioniert und zählt als Aktivität (HTTP ' . $s . ')');
[$s] = $call('POST', '/api/staff/v1/availability.php', ['status' => 'busy', 'note' => 'Meeting', 'staffId' => $ids['Andere']], $chef);
$check($s === 200 && $row('Andere')['status'] === 'busy' && $row('Andere')['note'] === 'Meeting' && (int) $row('Andere')['auto_offline'] === 0, 'Admin ändert den Status eines Mitarbeiters (API)');
[$s] = $call('POST', '/api/staff/v1/availability.php', ['status' => 'offline', 'staffId' => $ids['Chef']], $agent);
$check($s === 403 && $row('Chef')['status'] === null, 'Normaler Mitarbeiter darf fremde Status nicht ändern (HTTP ' . $s . ')');
[$s] = $call('POST', '/api/staff/v1/availability.php', ['status' => 'busy', 'staffId' => 99999], $chef);
$check($s === 404, 'Unbekannter Mitarbeiter: HTTP 404 (' . $s . ')');
[$s] = $call('POST', '/api/staff/v1/availability.php', ['status' => 'irgendwas', 'staffId' => $ids['Andere']], $chef);
$check($s === 422, 'Ungültiger Status wird abgelehnt (HTTP ' . $s . ')');
// 31 Minuten nichts getan: offline; wer aktiv war, bleibt
$call('POST', '/api/staff/v1/availability.php', ['status' => 'available'], $chef);
$setActive('Agent', 31);
$setActive('Andere', 5);
[$s, $team] = $call('GET', '/api/staff/v1/availability.php', null, $chef);
$byId = [];
foreach ($team['team'] ?? [] as $m) $byId[$m['id']] = $m;
$check($s === 200 && ($byId[$ids['Agent']]['status'] ?? '') === 'offline' && ($byId[$ids['Agent']]['autoOffline'] ?? false) === true, 'Nach 31 Minuten ohne Aktivität steht der Mitarbeiter auf Offline (automatisch)');
$check($row('Agent')['prev_status'] === 'available' && (int) $row('Agent')['auto_offline'] === 1, 'Der vorherige Status wird gemerkt');
$check(($byId[$ids['Andere']]['status'] ?? '') === 'busy' && ($byId[$ids['Chef']]['status'] ?? '') === 'available', 'Aktive Mitarbeiter bleiben unverändert ' . json_encode([$byId[$ids['Andere']] ?? null, $byId[$ids['Chef']] ?? null]));
// Hintergrund-Abrufe halten niemanden online
$before = $row('Agent')['last_active_at'];
$call('GET', '/api/staff/v1/availability.php', null, $agent);
$call('POST', '/api/staff/v1/push_device.php', ['action' => 'register', 'token' => 'devAgent_' . str_repeat('a', 40)], $agent);
$check($row('Agent')['last_active_at'] === $before && $row('Agent')['status'] === 'offline', 'Abfragen im Hintergrund und Push-Anmeldung zählen nicht als Aktivität');
// Berührungs-Ping der App holt aus dem automatischen Offline zurück
[$s, $r] = $call('POST', '/api/staff/v1/presence.php', [], $agent);
$check($s === 200 && ($r['status'] ?? '') === 'available' && $row('Agent')['status'] === 'available' && (int) $row('Agent')['auto_offline'] === 0 && $row('Agent')['prev_status'] === null, 'Aktivität (App-Ping) bringt den vorherigen Status zurück (HTTP ' . $s . ')');
[$s] = $call('POST', '/api/staff/v1/presence.php', []);
$check($s === 401, 'Präsenz-Ping nur mit Anmeldung');
// Ein vorheriger Status "Pause" kommt als Pause zurück
$call('POST', '/api/staff/v1/availability.php', ['status' => 'break'], $agent);
$setActive('Agent', 40);
$call('GET', '/api/staff/v1/availability.php', null, $chef);
$check($row('Agent')['status'] === 'offline' && $row('Agent')['prev_status'] === 'break', 'Auch „Pause“ geht nach Inaktivität auf Offline');
$call('POST', '/api/staff/v1/presence.php', [], $agent);
$check($row('Agent')['status'] === 'break', 'und kommt als „Pause“ zurück');
// Manuell gesetzter Status ist nie automatisch
$call('POST', '/api/staff/v1/availability.php', ['status' => 'offline'], $agent);
$setActive('Agent', 120);
$call('GET', '/api/staff/v1/availability.php', null, $chef);
$check((int) $row('Agent')['auto_offline'] === 0 && $row('Agent')['status'] === 'offline', 'Von Hand gesetztes Offline bleibt „manuell“');
$call('POST', '/api/staff/v1/availability.php', ['status' => 'busy', 'staffId' => $ids['Agent']], $chef);
$check($row('Agent')['status'] === 'busy' && (int) $row('Agent')['auto_offline'] === 0, 'Admin-Status überschreibt den automatischen Zustand');
// Weboberfläche: Admin ändert Status und stellt die Zeit ein
$jar = tempnam(sys_get_temp_dir(), 'act');
[, $lp] = $call('GET', '/staff/login.php', null, null, [], $jar);
preg_match('/name="csrf_token" value="([a-f0-9]+)"/', is_string($lp) ? $lp : '', $m);
$call('POST', '/staff/login.php', null, null, ['csrf_token' => $m[1] ?? '', 'email' => 'chef@test.de', 'password' => 'Sehr-Sicher-1234'], $jar);
[$s, $page] = $call('GET', '/staff/availability.php', null, null, [], $jar, ['Sec-Fetch-Mode: navigate']);
$page = is_string($page) ? $page : '';
$check($s === 200 && str_contains($page, 'Status der Mitarbeiter ändern') && str_contains($page, 'Automatisch offline nach'), 'Verfügbarkeitsseite zeigt dem Admin die Status-Verwaltung und die Zeit-Einstellung (HTTP ' . $s . ')');
preg_match('/name="csrf_token" value="([a-f0-9]+)"/', $page, $m);
$csrf = $m[1] ?? '';
// Das CSRF-Token wird nach jeder Anfrage erneuert: vor jeder Aktion die Seite neu laden
$fresh = function () use ($call, $jar): string {
[, $p] = $call('GET', '/staff/availability.php', null, null, [], $jar, ['Sec-Fetch-Mode: navigate']);
preg_match('/name="csrf_token" value="([a-f0-9]+)"/', is_string($p) ? $p : '', $mm);
return $mm[1] ?? '';
};
[$s] = $call('POST', '/staff/availability.php', null, null, ['csrf_token' => $csrf, 'action' => 'set_staff_status', 'staff_id' => (string) $ids['Andere'], 'status' => 'break', 'note' => 'Mittag'], $jar);
$check($s === 302 && $row('Andere')['status'] === 'break' && $row('Andere')['note'] === 'Mittag', 'Admin ändert den Status im Browser');
$audit = (int) $pdo()->query("SELECT COUNT(*) FROM admin_audit_log WHERE action LIKE 'Status von Mitarbeiter%'")->fetchColumn();
$check($audit >= 2, 'Statusänderungen durch Admins stehen im Aktivitätsprotokoll');
[$s] = $call('POST', '/staff/availability.php', null, null, ['csrf_token' => $fresh(), 'action' => 'save_auto_offline', 'auto_offline_minutes' => '10'], $jar);
$minutes = $pdo()->query("SELECT setting_value FROM settings WHERE setting_key = 'staff_auto_offline_minutes'")->fetchColumn();
$check($s === 302 && $minutes === '10', 'Zeit bis automatisch offline einstellbar (HTTP ' . $s . ')');
$setActive('Andere', 12);
$call('GET', '/staff/availability_status.php', null, null, [], $jar);
$check($row('Andere')['status'] === 'offline' && (int) $row('Andere')['auto_offline'] === 1, 'Mit 10 Minuten wird nach 12 Minuten ohne Aktivität offline gesetzt');
$call('POST', '/staff/availability.php', null, null, ['csrf_token' => $fresh(), 'action' => 'save_auto_offline', 'auto_offline_minutes' => '0'], $jar);
$call('POST', '/api/staff/v1/availability.php', ['status' => 'busy', 'staffId' => $ids['Andere']], $chef);
$setActive('Andere', 500);
$call('GET', '/staff/availability_status.php', null, null, [], $jar);
$check($row('Andere')['status'] === 'busy', '0 Minuten schaltet die Funktion aus');
// Normaler Mitarbeiter darf die Admin-Aktionen im Browser nicht ausführen
$jar2 = tempnam(sys_get_temp_dir(), 'act');
[, $lp] = $call('GET', '/staff/login.php', null, null, [], $jar2);
preg_match('/name="csrf_token" value="([a-f0-9]+)"/', is_string($lp) ? $lp : '', $m);
$call('POST', '/staff/login.php', null, null, ['csrf_token' => $m[1] ?? '', 'email' => 'agent@test.de', 'password' => 'Sehr-Sicher-1234'], $jar2);
[, $ap] = $call('GET', '/staff/availability.php', null, null, [], $jar2, ['Sec-Fetch-Mode: navigate']);
preg_match('/name="csrf_token" value="([a-f0-9]+)"/', is_string($ap) ? $ap : '', $m);
$check(is_string($ap) && !str_contains($ap, 'Status der Mitarbeiter ändern'), 'Normale Mitarbeiter sehen die Status-Verwaltung nicht');
$call('POST', '/staff/availability.php', null, null, ['csrf_token' => $m[1] ?? '', 'action' => 'set_staff_status', 'staff_id' => (string) $ids['Chef'], 'status' => 'offline'], $jar2);
$check($row('Chef')['status'] === 'available', 'Normale Mitarbeiter können den Status anderer auch per Formular nicht ändern');
@unlink($jar);
@unlink($jar2);
} finally {
if (isset($webProc) && is_resource($webProc)) { proc_terminate($webProc); proc_close($webProc); }
}
usleep(300000);
$rm = function (string $d) use (&$rm) {
foreach (scandir($d) ?: [] as $e) { if ($e === '.' || $e === '..') continue; is_dir("$d/$e") && !is_link("$d/$e") ? $rm("$d/$e") : @unlink("$d/$e"); }
@rmdir($d);
};
if (str_starts_with($work, sys_get_temp_dir() . '/deskhub-activity-')) $rm($work);
if ($failures) {
fwrite(STDERR, "Fehlgeschlagen:\n - " . implode("\n - ", $failures) . "\n");
exit(1);
}
echo "Staff activity checks passed ({$total} Prüfungen).\n";