Files
deskhub/DeskHub-Webseite/tests/department_auto_assign.php
T
2026-10-23 11:14:26 +00:00

212 lines
15 KiB
PHP

<?php
declare(strict_types=1);
/**
* Prüft die automatische Zuweisung neuer Tickets je Abteilung: fester Mitarbeiter (mit Vertretung im Urlaub), reihum, Vorrang von Ticket-Regeln,
* Speichern über die API der Apps und das Formular der Weboberfläche.
*/
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-assign-' . bin2hex(random_bytes(4));
$tmp = $work . '/inst';
mkdir($tmp, 0755, true);
$webPort = random_int(34000, 34499);
$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 $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 ($method === 'POST') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json ?? [])); }
$b = (string) curl_exec($ch);
$s = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
return [$s, json_decode($b, true) ?? $b];
};
[, $r] = $call('POST', '/api/staff/v1/login.php', ['email' => 'chef@test.de', 'password' => 'Sehr-Sicher-1234', 'deviceName' => 'T']);
$chef = (string) ($r['token'] ?? '');
$check($chef !== '', 'Anmeldung als Admin');
// API-Schlüssel für die öffentliche Ticket-API
$apiKey = 'dh_' . bin2hex(random_bytes(24));
$pdo()->prepare('INSERT INTO api_keys (name, key_hash, key_prefix, can_create_tickets, can_read_tickets, ip_whitelist, is_active, created_at) VALUES (?,?,?,?,?,?,1,?)')
->execute(['Test', hash('sha256', $apiKey), substr($apiKey, 0, 9), 1, 0, null, date('Y-m-d H:i:s')]);
$newTicket = function (int $deptId, string $subject = 'Minecraft Test') use ($call, $apiKey, $pdo): array {
[$s, $r] = $call('POST', '/api/public/v1/tickets.php', ['name' => 'MC', 'email' => 'mc@example.de', 'subject' => $subject, 'message' => 'x', 'departmentId' => $deptId], null, ['X-API-Key: ' . $apiKey]);
if ($s !== 201) return ['status' => $s, 'assignee' => null, 'log' => '', 'number' => ''];
$t = $pdo()->prepare('SELECT id, assigned_staff_id FROM tickets WHERE ticket_number = ?');
$t->execute([$r['number']]);
$row = $t->fetch();
$l = $pdo()->prepare("SELECT action FROM activity_log WHERE ticket_id = ? AND action LIKE 'Automatisch zugewiesen%'");
$l->execute([$row['id']]);
return ['status' => 201, 'assignee' => $row['assigned_staff_id'] === null ? null : (int) $row['assigned_staff_id'], 'log' => (string) $l->fetchColumn(), 'number' => $r['number']];
};
// Neue Abteilung "First Support" per Mitarbeiter-API anlegen (Apps und Windows-Programm nutzen dieselbe Schnittstelle)
[$s, $r] = $call('POST', '/api/staff/v1/departments.php', ['action' => 'save', 'id' => 0, 'name' => 'First Support', 'email' => '', 'autoAssignMode' => 'staff', 'autoAssignStaffId' => $ids['Agent']], $chef);
$first = (int) ($r['id'] ?? 0);
$check($s === 200 && $first > 0, 'Abteilung mit automatischer Zuweisung anlegen (HTTP ' . $s . ')');
[$s, $r] = $call('GET', '/api/staff/v1/departments.php', null, $chef);
$item = null;
foreach ($r['items'] ?? [] as $d) if ((int) $d['id'] === $first) $item = $d;
$check($item && $item['autoAssignMode'] === 'staff' && (int) $item['autoAssignStaffId'] === $ids['Agent'], 'Die Einstellung wird von der API geliefert');
// Fester Mitarbeiter
$t = $newTicket($first);
$check($t['status'] === 201 && $t['assignee'] === $ids['Agent'] && str_contains($t['log'], 'Einstellung der Abteilung'), 'Ticket über die API (z. B. Minecraft-Plugin) wird dem festen Mitarbeiter zugewiesen und im Verlauf vermerkt');
// Ticket-Regel hat Vorrang
$db = $pdo();
$db->prepare("INSERT INTO ticket_rules (name, match_type, is_active, sort_order, created_at) VALUES ('Regel', 'all', 1, 1, ?)")->execute([date('Y-m-d H:i:s')]);
$ruleId = (int) $db->lastInsertId();
$pdo()->prepare("INSERT INTO ticket_rule_conditions (rule_id, field, operator, value) VALUES (?, 'subject', 'contains', 'VORRANG')")->execute([$ruleId]);
$pdo()->prepare("INSERT INTO ticket_rule_actions (rule_id, action_type, action_value) VALUES (?, 'assign_staff', ?)")->execute([$ruleId, $ids['Andere']]);
$t = $newTicket($first, 'Test VORRANG');
$check($t['assignee'] === $ids['Andere'] && !str_contains($t['log'], 'Einstellung der Abteilung'), 'Eine Ticket-Regel mit „Mitarbeiter zuweisen“ hat Vorrang vor der Abteilung');
// Urlaub: Vertretung, ohne Vertretung unzugewiesen
$pdo()->prepare('UPDATE staff SET is_on_vacation = 1, vacation_substitute_id = ? WHERE id = ?')->execute([$ids['Andere'], $ids['Agent']]);
$t = $newTicket($first);
$check($t['assignee'] === $ids['Andere'], 'Ist der feste Mitarbeiter im Urlaub, bekommt seine Vertretung das Ticket');
$pdo()->prepare('UPDATE staff SET vacation_substitute_id = NULL WHERE id = ?')->execute([$ids['Agent']]);
$t = $newTicket($first);
$check($t['assignee'] === null, 'Im Urlaub ohne Vertretung bleibt das Ticket unzugewiesen');
$pdo()->prepare('UPDATE staff SET is_on_vacation = 0 WHERE id = ?')->execute([$ids['Agent']]);
$pdo()->prepare('UPDATE staff SET is_active = 0 WHERE id = ?')->execute([$ids['Agent']]);
$t = $newTicket($first);
$check($t['assignee'] === null, 'Ein deaktivierter Mitarbeiter bekommt nichts');
$pdo()->prepare('UPDATE staff SET is_active = 1 WHERE id = ?')->execute([$ids['Agent']]);
// Aus
[$s] = $call('POST', '/api/staff/v1/departments.php', ['action' => 'save', 'id' => $first, 'name' => 'First Support', 'email' => '', 'autoAssignMode' => 'none', 'autoAssignStaffId' => null], $chef);
$t = $newTicket($first);
$check($s === 200 && $t['assignee'] === null, 'Ausgeschaltet: Tickets bleiben wie bisher unzugewiesen');
// Prüfungen beim Speichern
[$s, $r] = $call('POST', '/api/staff/v1/departments.php', ['action' => 'save', 'id' => $first, 'name' => 'First Support', 'email' => '', 'autoAssignMode' => 'staff', 'autoAssignStaffId' => null], $chef);
$check($s === 422, 'Fester Mitarbeiter ohne Auswahl wird abgelehnt (HTTP ' . $s . ')');
[$s] = $call('POST', '/api/staff/v1/departments.php', ['action' => 'save', 'id' => $first, 'name' => 'First Support', 'email' => '', 'autoAssignMode' => 'wuerfeln'], $chef);
$check($s === 422, 'Unbekannte Art wird abgelehnt (HTTP ' . $s . ')');
[$s] = $call('POST', '/api/staff/v1/departments.php', ['action' => 'save', 'id' => $first, 'name' => 'First Support', 'email' => '', 'autoAssignMode' => 'staff', 'autoAssignStaffId' => 99999], $chef);
$check($s === 422, 'Unbekannter Mitarbeiter wird abgelehnt (HTTP ' . $s . ')');
// Ältere App-Version schickt die Felder nicht: Einstellung bleibt unverändert
$call('POST', '/api/staff/v1/departments.php', ['action' => 'save', 'id' => $first, 'name' => 'First Support', 'email' => '', 'autoAssignMode' => 'staff', 'autoAssignStaffId' => $ids['Agent']], $chef);
[$s] = $call('POST', '/api/staff/v1/departments.php', ['action' => 'save', 'id' => $first, 'name' => 'First Support (alt)', 'email' => ''], $chef);
$mode = $pdo()->query("SELECT auto_assign_mode FROM departments WHERE id = $first")->fetchColumn();
$check($s === 200 && $mode === 'staff', 'Ältere App-Versionen lassen die Einstellung unverändert');
// Reihum: Mitglieder der Abteilung (Hauptabteilung) werden der Reihe nach bedient
$rr = $dept; // Standardabteilung mit Chef, Agent, Andere als Mitgliedern
$pdo()->prepare("UPDATE departments SET auto_assign_mode = 'round_robin' WHERE id = ?")->execute([$rr]);
$seq = [];
for ($i = 0; $i < 6; $i++) $seq[] = $newTicket($rr)['assignee'];
$counts = array_count_values(array_map('strval', $seq));
$check(count($counts) === 3 && min($counts) === 2 && max($counts) === 2, 'Reihum: jedes der drei Mitglieder bekommt gleich viele Tickets (' . json_encode($seq) . ')');
$check($seq[0] !== $seq[1] && $seq[1] !== $seq[2] && $seq[0] === $seq[3], 'Reihum: der Reihe nach, dann wieder von vorn');
// Urlaub und Offline werden übersprungen
$pdo()->prepare('UPDATE staff SET is_on_vacation = 1 WHERE id = ?')->execute([$ids['Agent']]);
$pdo()->prepare("INSERT INTO staff_availability (staff_id, status, updated_at) VALUES (?, 'offline', ?)")->execute([$ids['Andere'], date('Y-m-d H:i:s')]);
$seq = [];
for ($i = 0; $i < 3; $i++) $seq[] = $newTicket($rr)['assignee'];
$check($seq === [$ids['Chef'], $ids['Chef'], $ids['Chef']], 'Reihum überspringt Mitarbeiter im Urlaub oder offline (' . json_encode($seq) . ')');
// Alle offline: trotzdem wird zugewiesen (an die, die im Urlaub nicht sind)
$pdo()->prepare("INSERT INTO staff_availability (staff_id, status, updated_at) VALUES (?, 'offline', ?)")->execute([$ids['Chef'], date('Y-m-d H:i:s')]);
$seq = [];
for ($i = 0; $i < 2; $i++) $seq[] = $newTicket($rr)['assignee'];
$check(!in_array(null, $seq, true) && !in_array($ids['Agent'], $seq, true), 'Sind alle erreichbaren offline, bekommt trotzdem jemand (nicht der im Urlaub) das Ticket (' . json_encode($seq) . ')');
// Reihum in einer Abteilung ohne Mitglieder: unzugewiesen
$db = $pdo();
$db->prepare('INSERT INTO departments (name, email, is_active, auto_assign_mode, created_at) VALUES (?,?,1,?,?)')->execute(['Leer', '', 'round_robin', date('Y-m-d H:i:s')]);
$empty = (int) $db->lastInsertId();
$check($newTicket($empty)['assignee'] === null, 'Reihum ohne Mitglieder lässt das Ticket unzugewiesen');
// Web-Formular der Abteilung zeigt die Einstellung
$jar = tempnam(sys_get_temp_dir(), 'asg');
$ch = curl_init("http://127.0.0.1:$webPort/staff/login.php");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEJAR => $jar, CURLOPT_COOKIEFILE => $jar]);
$lp = (string) curl_exec($ch);
preg_match('/name="csrf_token" value="([a-f0-9]+)"/', $lp, $m);
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query(['csrf_token' => $m[1] ?? '', 'email' => 'chef@test.de', 'password' => 'Sehr-Sicher-1234'])]);
curl_exec($ch);
curl_setopt_array($ch, [CURLOPT_URL => "http://127.0.0.1:$webPort/staff/departments.php?edit=$first", CURLOPT_HTTPGET => true, CURLOPT_HTTPHEADER => ['Sec-Fetch-Mode: navigate']]);
$page = (string) curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
$check($code === 200 && str_contains($page, 'Neue Tickets automatisch zuweisen') && str_contains($page, 'Reihum an die Mitarbeiter der Abteilung') && preg_match('/<option value="staff" selected>/', $page) === 1, 'Web-Formular der Abteilung zeigt die Einstellung (HTTP ' . $code . ')');
@unlink($jar);
// Datenbank noch nicht aktualisiert (Spalte fehlt): Speichern meldet verständlich 503 statt eines nackten Serverfehlers, Tickets entstehen weiter
$pdo()->exec('ALTER TABLE departments DROP COLUMN auto_assign_mode');
[$s, $r] = $call('POST', '/api/staff/v1/departments.php', ['action' => 'save', 'id' => $first, 'name' => 'First Support', 'email' => '', 'autoAssignMode' => 'staff', 'autoAssignStaffId' => $ids['Agent']], $chef);
$check($s === 503 && str_contains(json_encode($r, JSON_UNESCAPED_UNICODE), 'Datenbank aktualisieren'), 'Fehlende Datenbank-Spalte: verständliche Meldung statt Serverfehler (HTTP ' . $s . ')');
$t = $newTicket($first);
$check($t['status'] === 201 && $t['assignee'] === null, 'Fehlende Datenbank-Spalte: Tickets werden trotzdem angelegt (unzugewiesen)');
} 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-assign-')) $rm($work);
if ($failures) {
fwrite(STDERR, "Fehlgeschlagen:\n - " . implode("\n - ", $failures) . "\n");
exit(1);
}
echo "Department auto-assign checks passed ({$total} Prüfungen).\n";