Upload via GUI (258 Dateien)
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
/**
|
||||
* staff/_dashboard_recent_partial.php
|
||||
*
|
||||
* Rendert NUR die "Priorisiert"-Tabelle des Dashboards. Wird von staff/dashboard.php an
|
||||
* zwei Stellen genutzt: normal beim vollständigen Seitenaufbau, und bei ?recent_partial=1
|
||||
* als einziger Output für den Live-Refresh per JS (siehe <script> weiter unten in
|
||||
* dashboard.php) – ohne das wäre z.B. ein Ticket, das per App geschlossen wurde, hier erst
|
||||
* nach einem manuellen Reload verschwunden (siehe Nutzerrückmeldung: App zeigte
|
||||
* "Geschlossen", das Dashboard hier noch "Offen", bis neu geladen wurde).
|
||||
* Erwartet die von dashboard.php bereits berechnete Variable $recent.
|
||||
*/
|
||||
?>
|
||||
<div id="dashboard-recent-region">
|
||||
<h3>Priorisiert (mir zugewiesen oder unbearbeitet)</h3>
|
||||
<div class="card">
|
||||
<?php if (!$recent): ?>
|
||||
<div class="empty-state">Keine offenen Tickets – gute Arbeit!</div>
|
||||
<?php else: ?>
|
||||
<table>
|
||||
<thead><tr><th>Ticket</th><th>Betreff</th><th>Abteilung</th><th>Priorität</th><th>Status</th><th>Fällig</th></tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($recent as $t):
|
||||
[$label, $color] = status_label($t['status']);
|
||||
$isOverdue = $t['resolution_due_at'] && strtotime($t['resolution_due_at']) < time();
|
||||
?>
|
||||
<tr class="<?= $isOverdue ? 'is-overdue' : '' ?>">
|
||||
<td><a href="/staff/ticket_view.php?n=<?= urlencode($t['ticket_number']) ?>" class="ticket-no">#<?= e($t['ticket_number']) ?></a></td>
|
||||
<td>
|
||||
<a href="/staff/ticket_view.php?n=<?= urlencode($t['ticket_number']) ?>"><?= e($t['subject']) ?></a><br>
|
||||
<span class="muted" style="font-size:.78rem"><?= e($t['requester_name']) ?></span>
|
||||
<span class="muted" style="font-size:.75rem; color:var(--muted-lt)"> · <?= e($t['requester_email']) ?></span>
|
||||
</td>
|
||||
<td><?= e($t['department_name']) ?></td>
|
||||
<td><span class="badge" style="background:<?= e($t['priority_color']) ?>"><?= e($t['priority_name']) ?></span></td>
|
||||
<td><span class="badge" style="background:<?= $color ?>"><?= e($label) ?></span></td>
|
||||
<td class="muted"><?= time_until($t['resolution_due_at']) ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,5 @@
|
||||
</main>
|
||||
</div>
|
||||
<script src="/assets/js/richtext.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,410 @@
|
||||
<?php
|
||||
/** @var array $staff (current_staff(), wird von der aufrufenden Seite gesetzt) */
|
||||
$staff = current_staff();
|
||||
$activePage = $activePage ?? '';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title><?= e($pageTitle ?? 'DeskHub – Mitarbeiterbereich') ?></title>
|
||||
<meta name="csrf" content="<?= csrf_token() ?>">
|
||||
<?php
|
||||
// VAPID Public Key – aus Config oder automatisch aus DB
|
||||
if (file_exists(__DIR__ . '/../includes/push.php')) {
|
||||
require_once __DIR__ . '/../includes/push.php';
|
||||
$__vapidKeys = get_or_create_vapid_keys();
|
||||
$pushKey = $__vapidKeys['public_key'] ?? '';
|
||||
} else {
|
||||
$pushKey = config()['push']['public_key'] ?? '';
|
||||
}
|
||||
?>
|
||||
<?php if ($pushKey): ?>
|
||||
<meta name="push-key" content="<?= e($pushKey) ?>">
|
||||
<?php endif; ?>
|
||||
<link rel="stylesheet" href="/assets/css/style.css?v=<?= @filemtime(__DIR__ . "/../assets/css/style.css") ?: time() ?>">
|
||||
<link rel="icon" href="/favicon.ico" sizes="any">
|
||||
<link rel="icon" href="/assets/icons/icon-192.png" type="image/png">
|
||||
<link rel="manifest" href="/manifest-staff.php">
|
||||
<meta name="theme-color" content="#0f6f6a">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<link rel="apple-touch-icon" href="/assets/icons/icon-192.png">
|
||||
<?php $faviconLogo = get_setting('logo_path'); if ($faviconLogo): ?>
|
||||
<link rel="icon" href="<?= e($faviconLogo) ?>">
|
||||
<?php endif; ?>
|
||||
<script>
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/staff/sw-staff.js', {scope: '/staff/'}).catch(function(){});
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="app-shell">
|
||||
<aside class="sidebar">
|
||||
<div class="brand">
|
||||
<?php $logo = get_setting('logo_path'); ?>
|
||||
<?php if ($logo): ?>
|
||||
<img src="<?= e($logo) ?>" alt="<?= e(get_setting('display_name', 'DeskHub')) ?>" style="max-height:34px; max-width:180px; display:block">
|
||||
<?php else: ?>
|
||||
Desk<span>Hub</span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<nav>
|
||||
<?php // Übersicht + ehemals separates "Berichte" wurden zu einer Seite zusammengelegt
|
||||
// (siehe staff/reports.php) – der Login landete ohnehin schon immer dort. ?>
|
||||
<a href="/staff/reports.php" class="<?= $activePage==='reports'?'active':'' ?>">Übersicht</a>
|
||||
<a href="/staff/report_builder.php" class="<?= $activePage==='report_builder'?'active':'' ?>">Bericht-Baukasten</a>
|
||||
<a href="/staff/tickets.php" class="<?= $activePage==='tickets'?'active':'' ?>">Tickets</a>
|
||||
<a href="/staff/tasks.php" class="<?= $activePage==='tasks'?'active':'' ?>">Aufgaben</a>
|
||||
<a href="/staff/banlist.php" class="<?= $activePage==='banlist'?'active':'' ?>">Sperrliste</a>
|
||||
<a href="/staff/agent_directory.php" class="<?= $activePage==='agent_directory'?'active':'' ?>">Verzeichnis</a>
|
||||
<a href="/staff/apps.php" class="<?= $activePage==='apps'?'active':'' ?>">Apps</a>
|
||||
<?php foreach (plugin_menu_items($staff ?? null) as $__pm): ?>
|
||||
<a href="<?= e($__pm['url']) ?>" class="<?= ($activePage ?? '') === 'plugin_' . $__pm['plugin'] ? 'active' : '' ?>"><?= e($__pm['label']) ?></a>
|
||||
<?php endforeach; ?>
|
||||
<?php if (get_setting('live_chat_enabled', '0') === '1' && $staff): ?>
|
||||
<?php
|
||||
// Badge = Anzahl Live-Chats, deren letzte Nachricht vom Kunden kam (also unbeantwortet),
|
||||
// auf die eigenen Abteilungen begrenzt (wie die Ticketliste selbst).
|
||||
[$__lcDeptSql, $__lcDeptParams] = dept_filter_sql(staff_department_ids($staff), 't.department_id');
|
||||
$__lcSql = "SELECT COUNT(*) FROM tickets t WHERE t.source = 'chat' AND t.status != 'closed'
|
||||
AND (SELECT tt.author_type FROM ticket_threads tt WHERE tt.ticket_id = t.id ORDER BY tt.created_at DESC, tt.id DESC LIMIT 1) = 'customer'"
|
||||
. ($__lcDeptSql !== '' ? " AND $__lcDeptSql" : '');
|
||||
$__lcStmt = get_db()->prepare($__lcSql);
|
||||
$__lcStmt->execute($__lcDeptParams);
|
||||
$__lcPending = (int) $__lcStmt->fetchColumn();
|
||||
?>
|
||||
<a href="/staff/live_chat.php" class="<?= $activePage==='live_chat'?'active':'' ?>">
|
||||
Live-Chat<?php if ($__lcPending): ?> <span class="nav-badge" style="background:var(--danger, #dc2626); color:#fff; border-radius:10px; min-width:18px; height:18px; font-size:.68rem; font-weight:700; display:inline-flex; align-items:center; justify-content:center; padding:0 5px; margin-left:4px; vertical-align:middle"><?= $__lcPending > 9 ? '9+' : $__lcPending ?></span><?php endif; ?>
|
||||
</a>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php
|
||||
// Adminportal auch für "Co-Admins" zeigen: Agenten, denen per benutzerdefinierter Rolle
|
||||
// gezielt einzelne Adminportal-Rechte zugewiesen wurden (admin_section_permissions()).
|
||||
// has_permission() liefert für echte Admins ohnehin immer true, daher genügt die reine
|
||||
// Rechteprüfung je Link – kein zusätzliches role==='admin' nötig.
|
||||
$hasAnyAdminAccess = false;
|
||||
if ($staff) {
|
||||
foreach (array_keys(admin_section_permissions()) as $__perm) {
|
||||
if (has_permission($staff, $__perm)) { $hasAnyAdminAccess = true; break; }
|
||||
}
|
||||
}
|
||||
?>
|
||||
<?php if ($hasAnyAdminAccess): ?>
|
||||
<div class="nav-section-label" id="admin-toggle" role="button" tabindex="0">
|
||||
Adminportal <span class="nav-toggle-chevron">▾</span>
|
||||
</div>
|
||||
<div class="nav-admin-block" id="admin-block">
|
||||
<span class="nav-group-label">Verwalten</span>
|
||||
<?php if (has_permission($staff, 'manage_departments')): ?><a href="/staff/departments.php" class="<?= $activePage==='departments'?'active':'' ?>">Abteilungen</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'manage_priorities')): ?><a href="/staff/priorities.php" class="<?= $activePage==='priorities'?'active':'' ?>">Prioritäten / SLA</a><a href="/staff/sla_plans.php" class="<?= $activePage==='sla_plans'?'active':'' ?>">SLA-Pläne</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'manage_help_topics')): ?><a href="/staff/help_topics.php" class="<?= $activePage==='help_topics'?'active':'' ?>">Hilfethemen</a><?php endif; ?>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/custom_fields.php" class="<?= $activePage==='custom_fields'?'active':'' ?>">Ticket-Felder</a><?php endif; ?>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/api_keys.php" class="<?= $activePage==='api_keys'?'active':'' ?>">API-Schlüssel</a><a href="/staff/webhooks.php" class="<?= $activePage==='webhooks'?'active':'' ?>">Webhooks</a><?php endif; ?>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/custom_lists.php" class="<?= $activePage==='custom_lists'?'active':'' ?>">Benutzerdefinierte Listen</a><?php endif; ?>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/canned_responses.php" class="<?= $activePage==='canned'?'active':'' ?>">Vorlagen</a><?php endif; ?>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/site_pages.php" class="<?= $activePage==='site_pages'?'active':'' ?>">Seiten</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'manage_email_addresses')): ?><a href="/staff/email_addresses.php" class="<?= $activePage==='email_addresses'?'active':'' ?>">E-Mail-Adressen</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'manage_email_templates')): ?><a href="/staff/email_templates.php" class="<?= $activePage==='email_templates'?'active':'' ?>">E-Mail-Vorlagen</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'manage_kb')): ?><a href="/staff/kb_manage.php" class="<?= $activePage==='kb'?'active':'' ?>">Wissensdatenbank</a><?php endif; ?>
|
||||
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/plugins.php" class="<?= $activePage==='plugins'?'active':'' ?>">Plugins</a><?php endif; ?>
|
||||
<span class="nav-group-label">Kunden</span>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/customers.php" class="<?= $activePage==='customers'?'active':'' ?>">Kundenverzeichnis</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'manage_organizations')): ?><a href="/staff/organizations.php" class="<?= $activePage==='organizations'?'active':'' ?>">Organisationen</a><?php endif; ?>
|
||||
|
||||
<span class="nav-group-label">Agenten</span>
|
||||
<?php if (has_permission($staff, 'manage_staff')): ?><a href="/staff/staff_manage.php" class="<?= $activePage==='staff'?'active':'' ?>">Mitarbeiter</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'manage_teams')): ?><a href="/staff/teams.php" class="<?= $activePage==='teams'?'active':'' ?>">Teams</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'manage_roles')): ?><a href="/staff/roles.php" class="<?= $activePage==='roles'?'active':'' ?>">Rollen</a><?php endif; ?>
|
||||
|
||||
<span class="nav-group-label">System</span>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/security_check.php" class="<?= $activePage==='security_check'?'active':'' ?>">Sicherheitsprüfung</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'view_audit_log')): ?><a href="/staff/audit_log.php" class="<?= $activePage==='audit_log'?'active':'' ?>">Admin-Protokoll</a><?php endif; ?>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/ticket_rules.php" class="<?= $activePage==='ticket_rules'?'active':'' ?>">Ticket-Regeln</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'manage_escalations')): ?><a href="/staff/escalation_rules.php" class="<?= $activePage==='escalation_rules'?'active':'' ?>">Eskalationsregeln</a><?php endif; ?>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/recurring_tickets.php" class="<?= $activePage==='recurring'?'active':'' ?>">Wiederkehrende Tickets</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'view_time_entries')): ?><a href="/staff/time_entries.php" class="<?= $activePage==='time_entries'?'active':'' ?>">Zeiterfassung</a><?php endif; ?>
|
||||
<?php if (has_permission($staff, 'manage_business_hours')): ?><a href="/staff/business_hours.php" class="<?= $activePage==='business_hours'?'active':'' ?>">Geschäftszeiten</a><?php endif; ?>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/settings.php" class="<?= $activePage==='settings'?'active':'' ?>">Einstellungen</a><?php endif; ?>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/backup.php" class="<?= $activePage==='backup'?'active':'' ?>">Backup</a><?php endif; ?>
|
||||
<?php if ($staff['role'] === 'admin'): ?><a href="/staff/update.php" class="<?= $activePage==='update'?'active':'' ?>">System-Update</a><?php endif; ?>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
var toggle = document.getElementById('admin-toggle');
|
||||
var block = document.getElementById('admin-block');
|
||||
var KEY = 'deskhub_admin_nav_collapsed';
|
||||
// In diesen Adminportal-Unterseiten immer ausgeklappt zeigen, damit die aktive Seite sichtbar bleibt
|
||||
var forceOpen = block.querySelector('a.active') !== null;
|
||||
function apply(collapsed) {
|
||||
block.style.display = collapsed ? 'none' : '';
|
||||
toggle.querySelector('.nav-toggle-chevron').textContent = collapsed ? '▸' : '▾';
|
||||
}
|
||||
var stored = localStorage.getItem(KEY);
|
||||
apply(!forceOpen && stored === '1');
|
||||
toggle.addEventListener('click', function () {
|
||||
var collapsed = block.style.display !== 'none';
|
||||
apply(collapsed);
|
||||
localStorage.setItem(KEY, collapsed ? '1' : '0');
|
||||
});
|
||||
toggle.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle.click(); }
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<?php endif; ?>
|
||||
</nav>
|
||||
<div class="sidebar-footer">
|
||||
<?php if ($staff): ?>
|
||||
<div style="display:flex; align-items:center; gap:10px; margin-bottom:8px">
|
||||
<?php if (!empty($staff['avatar_path'])): ?>
|
||||
<img src="<?= e($staff['avatar_path']) ?>" alt="" style="width:32px; height:32px; border-radius:50%; object-fit:cover; flex-shrink:0; border:1px solid #2a3744">
|
||||
<?php else: ?>
|
||||
<div style="width:32px; height:32px; border-radius:50%; background:rgba(15,111,106,.3); display:flex; align-items:center; justify-content:center; font-size:.85rem; font-weight:700; color:#8bc4c2; flex-shrink:0">
|
||||
<?= mb_strtoupper(mb_substr($staff['name'], 0, 1)) ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<div style="min-width:0">
|
||||
<div style="font-size:.82rem; font-weight:600; color:#fff; overflow:hidden; text-overflow:ellipsis; white-space:nowrap"><?= e($staff['name']) ?></div>
|
||||
<div style="font-size:.72rem; color:#4e6278"><?= $staff['role']==='admin'?'Administrator':'Mitarbeiter' ?></div>
|
||||
<?php if (!empty($staff['is_on_vacation'])): ?>
|
||||
<div style="font-size:.7rem; color:var(--accent)">🌴 Im Urlaub</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:flex; gap:14px; align-items:center">
|
||||
|
||||
<?php
|
||||
$__unreadMentions = 0;
|
||||
$__unreadChat = 0;
|
||||
if ($staff) {
|
||||
$__ms = get_db()->prepare('SELECT COUNT(*) FROM staff_mentions WHERE mentioned_staff_id=? AND is_read=0');
|
||||
$__ms->execute([$staff['id']]);
|
||||
$__unreadMentions = (int)$__ms->fetchColumn();
|
||||
$__cs = get_db()->prepare('SELECT COUNT(*) FROM staff_chat_messages WHERE to_staff_id=? AND is_read=0');
|
||||
$__cs->execute([$staff['id']]);
|
||||
$__unreadChat = (int)$__cs->fetchColumn();
|
||||
}
|
||||
?>
|
||||
<a href="/staff/chat.php" title="Interner Chat" style="position:relative; color:#8b97a3; font-size:.78rem; text-decoration:none">
|
||||
💬<?php if ($__unreadChat > 0): ?><span style="position:absolute;top:-6px;right:-8px;background:#dc2626;color:#fff;border-radius:50%;font-size:.6rem;font-weight:700;width:15px;height:15px;display:flex;align-items:center;justify-content:center;line-height:1"><?= $__unreadChat > 9 ? '9+' : $__unreadChat ?></span><?php endif; ?>
|
||||
</a>
|
||||
<a href="/staff/mentions.php" title="Erwähnungen" style="position:relative; color:#8b97a3; font-size:.78rem; text-decoration:none">
|
||||
🔔<?php if ($__unreadMentions > 0): ?><span style="position:absolute;top:-6px;right:-8px;background:#dc2626;color:#fff;border-radius:50%;font-size:.6rem;font-weight:700;width:15px;height:15px;display:flex;align-items:center;justify-content:center;line-height:1"><?= $__unreadMentions > 9 ? '9+' : $__unreadMentions ?></span><?php endif; ?>
|
||||
</a>
|
||||
<a href="/staff/profile.php" style="color:#8b97a3; font-size:.78rem">Profil</a>
|
||||
<a href="/staff/logout.php" style="color:#8b97a3; font-size:.78rem">Abmelden</a>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<?php
|
||||
// Timeout in JS übergeben
|
||||
$_jsTimeout = (int)(get_setting('staff_session_timeout', '30') ?: 30);
|
||||
$_jsLastAct = $_SESSION['staff_last_activity'] ?? time();
|
||||
if (!isset($_SESSION['staff_last_activity'])) {
|
||||
$_SESSION['staff_last_activity'] = time();
|
||||
$_jsLastAct = time();
|
||||
}
|
||||
$_jsRemaining = max(10, ($_jsLastAct + $_jsTimeout * 60) - time());
|
||||
?>
|
||||
<script>
|
||||
window.sessionTimerRemaining = <?= (int)$_jsRemaining ?>;
|
||||
window.sessionTimerTimeout = <?= (int)$_jsTimeout ?>;
|
||||
</script>
|
||||
<script>
|
||||
(function() {
|
||||
var remaining = window.sessionTimerRemaining || 0;
|
||||
var timeoutMin = window.sessionTimerTimeout || 30;
|
||||
|
||||
function init() {
|
||||
var el = document.getElementById('session-timer');
|
||||
var bar = document.getElementById('session-timer-bar');
|
||||
if (!el || !bar || remaining <= 0) return;
|
||||
|
||||
function fmt(s) {
|
||||
var m = Math.floor(s / 60);
|
||||
var sec = s % 60;
|
||||
return m + ':' + (sec < 10 ? '0' : '') + sec;
|
||||
}
|
||||
|
||||
function tick() {
|
||||
if (remaining <= 0) {
|
||||
window.location.href = '/staff/login.php';
|
||||
return;
|
||||
}
|
||||
|
||||
el.textContent = fmt(remaining);
|
||||
|
||||
// Immer sichtbar
|
||||
bar.style.opacity = '1';
|
||||
bar.style.pointerEvents = 'auto';
|
||||
|
||||
// Farbe nach Dringlichkeit
|
||||
if (remaining <= 60) {
|
||||
bar.style.background = 'rgba(239,68,68,.9)';
|
||||
bar.style.borderColor = 'rgba(239,68,68,.5)';
|
||||
el.style.color = '#fff';
|
||||
} else if (remaining <= 300) {
|
||||
bar.style.background = 'rgba(245,158,11,.9)';
|
||||
bar.style.borderColor = 'rgba(245,158,11,.5)';
|
||||
el.style.color = '#fff';
|
||||
} else {
|
||||
bar.style.background = 'rgba(15,23,42,.72)';
|
||||
bar.style.borderColor = 'rgba(255,255,255,.1)';
|
||||
el.style.color = '#cbd5e1';
|
||||
}
|
||||
|
||||
remaining--;
|
||||
setTimeout(tick, 1000);
|
||||
}
|
||||
|
||||
tick();
|
||||
|
||||
// Bei jeder Nutzeraktion (Klick, Tastatur) Timer via fetch zurücksetzen
|
||||
var resetDebounce;
|
||||
function resetTimer() {
|
||||
clearTimeout(resetDebounce);
|
||||
resetDebounce = setTimeout(function() {
|
||||
fetch('/staff/session_ping.php', { method:'POST',
|
||||
headers:{'X-CSRF-Token': document.querySelector('meta[name=csrf]')?.content || ''},
|
||||
credentials:'same-origin' })
|
||||
.then(function(r){ return r.json(); })
|
||||
.then(function(d){ if (d.remaining) remaining = d.remaining; })
|
||||
.catch(function(){});
|
||||
}, 2000); // max. alle 2 Sek. ein Ping
|
||||
}
|
||||
|
||||
['click','keydown','mousemove','scroll','touchstart'].forEach(function(ev) {
|
||||
document.addEventListener(ev, resetTimer, { passive: true });
|
||||
});
|
||||
} // end init
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script>
|
||||
// ── Browser Push Notifications ───────────────────────────────────────────
|
||||
(function() {
|
||||
var pushKey = document.querySelector('meta[name=push-key]')?.content || document.getElementById('push-vapid-key')?.value;
|
||||
if (!pushKey || !('serviceWorker' in navigator) || !('PushManager' in window)) return;
|
||||
var btn = document.getElementById('push-toggle-btn');
|
||||
|
||||
function urlB64ToUint8(b64) {
|
||||
var pad = '='.repeat((4 - b64.length % 4) % 4);
|
||||
var raw = atob(b64.replace(/-/g,'+').replace(/_/g,'/') + pad);
|
||||
return Uint8Array.from([...raw].map(function(ch){ return ch.charCodeAt(0); }));
|
||||
}
|
||||
|
||||
function setBtn(active) {
|
||||
if (!btn) return;
|
||||
btn.textContent = active ? '🔔' : '🔕';
|
||||
btn.style.color = active ? '#22c55e' : '#8b97a3';
|
||||
btn.title = active ? 'Push aktiv – klicken zum Deaktivieren' : 'Push-Benachrichtigungen aktivieren';
|
||||
}
|
||||
|
||||
navigator.serviceWorker.ready.then(function(reg) {
|
||||
reg.pushManager.getSubscription().then(function(s) {
|
||||
setBtn(!!(s && Notification.permission === 'granted'));
|
||||
});
|
||||
});
|
||||
|
||||
window.togglePushNotifications = function() {
|
||||
navigator.serviceWorker.ready.then(function(reg) {
|
||||
reg.pushManager.getSubscription().then(function(sub) {
|
||||
if (sub) {
|
||||
sub.unsubscribe().then(function() {
|
||||
fetch('/staff/push_subscribe.php', { method:'POST', credentials:'same-origin',
|
||||
headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify({action:'unsubscribe', endpoint: sub.endpoint}) });
|
||||
setBtn(false);
|
||||
});
|
||||
} else {
|
||||
Notification.requestPermission().then(function(perm) {
|
||||
if (perm !== 'granted') { alert('Bitte Benachrichtigungen im Browser erlauben.'); return; }
|
||||
reg.pushManager.subscribe({ userVisibleOnly:true, applicationServerKey: urlB64ToUint8(pushKey) })
|
||||
.then(function(ns) {
|
||||
var j = ns.toJSON();
|
||||
fetch('/staff/push_subscribe.php', { method:'POST', credentials:'same-origin',
|
||||
headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify({action:'subscribe', endpoint:j.endpoint, keys:j.keys}) })
|
||||
.then(function() { setBtn(true); });
|
||||
}).catch(function(err) { alert('Push fehlgeschlagen: ' + err.message); });
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
})();
|
||||
</script>
|
||||
<main class="main">
|
||||
<!-- Session-Timer: kompakte Pille oben rechts -->
|
||||
<div id="session-timer-bar" style="position:fixed;top:12px;right:16px;z-index:9999;display:flex;align-items:center;gap:6px;background:rgba(15,23,42,.75);backdrop-filter:blur(6px);border:1px solid rgba(255,255,255,.1);border-radius:20px;padding:4px 12px 4px 8px;pointer-events:none;opacity:0;transition:opacity .3s">
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
|
||||
<span id="session-timer" style="font-size:.72rem;font-weight:700;color:#cbd5e1;font-variant-numeric:tabular-nums;letter-spacing:.02em"></span>
|
||||
</div>
|
||||
<?php foreach (get_flashes() as $f): ?>
|
||||
<div class="flash <?= e($f['type']) ?>"><?= e($f['message']) ?></div>
|
||||
<?php endforeach; ?>
|
||||
<?php
|
||||
if (isset($staff) && has_permission($staff, 'manage_email_addresses')) {
|
||||
foreach (system_health(get_db()) as $__issue): ?>
|
||||
<div class="flash <?= $__issue['level'] === 'error' ? 'error' : 'warning' ?>" style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
|
||||
<strong><?= $__issue['level'] === 'error' ? 'Störung:' : 'Hinweis:' ?></strong> <?= e($__issue['message']) ?>
|
||||
<a href="/staff/email_addresses.php" style="margin-left:auto">E-Mail-Adressen öffnen</a>
|
||||
</div>
|
||||
<?php endforeach; } ?>
|
||||
<?php
|
||||
if (isset($staff) && ($staff['role'] ?? '') === 'admin' && ($activePage ?? '') !== 'update') {
|
||||
require_once __DIR__ . '/../database/migrate.php';
|
||||
$__pending = migrations_pending(get_db());
|
||||
if ($__pending): ?>
|
||||
<div class="flash warning" style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
|
||||
<strong>Datenbank veraltet:</strong> <?= count($__pending) ?> ausstehende Änderung(en) – der Code ist neuer als die Datenbank.
|
||||
<a href="/staff/update.php" style="margin-left:auto">Jetzt aktualisieren</a>
|
||||
</div>
|
||||
<?php endif; } ?>
|
||||
<?php
|
||||
if (isset($staff) && ($staff['role'] ?? '') === 'admin' && ($activePage ?? '') !== 'plugins' && plugin_official_configured()) {
|
||||
$__upd = plugin_updates_available(get_db());
|
||||
if ($__upd): ?>
|
||||
<div class="flash warning" style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
|
||||
<strong>Plugin-Updates verfügbar:</strong> <?= e(implode(', ', array_map(fn($u) => $u['name'] . ' ' . $u['available'], $__upd))) ?>
|
||||
<a href="/staff/plugins.php" style="margin-left:auto">Zu den Plugins</a>
|
||||
</div>
|
||||
<?php endif; } ?>
|
||||
<?php $lockedOverride = get_locked_ticket_override(); ?>
|
||||
<?php if ($lockedOverride && isset($staff) && $staff['role'] === 'admin'): ?>
|
||||
<div class="flash warning" style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
|
||||
🔓 Als Admin können Sie die Sperre von „<?= e($lockedOverride['name']) ?>“ auf Ticket #<?= e($lockedOverride['number']) ?> sofort aufheben, statt auf den automatischen Timeout zu warten.
|
||||
<form method="post" action="/staff/ticket_view.php?n=<?= urlencode($lockedOverride['number']) ?>" style="margin:0">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="admin_force_unlock">
|
||||
<input type="hidden" name="locked_by_name" value="<?= e($lockedOverride['name']) ?>">
|
||||
<button type="submit" class="btn btn-sm" style="padding:4px 10px;font-size:.78rem">Sperre jetzt aufheben</button>
|
||||
</form>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php if (isset($staff) && $staff['role'] === 'admin' && (config()['db']['driver'] ?? 'sqlite') === 'sqlite'): ?>
|
||||
<div class="flash warning" style="display:flex;align-items:center;gap:10px">
|
||||
⚠️ <strong>SQLite-Modus aktiv:</strong> Nicht für den Produktivbetrieb geeignet.
|
||||
Bitte in <code>config/config.php</code> auf <code>driver = 'mysql'</code> umstellen und MySQL-Zugangsdaten eintragen.
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php if (isset($staff) && $staff['role'] === 'admin' && empty(config()['app_key']) && !get_setting('app_key')): ?>
|
||||
<div class="flash warning" style="display:flex;align-items:center;gap:10px">
|
||||
🔑 <strong>Kein App-Key gesetzt:</strong> Passwörter werden nur schwach verschlüsselt.
|
||||
Bitte in <code>config/config.php</code> den Wert <code>app_key</code> setzen.
|
||||
Generieren: <code>php -r "echo bin2hex(random_bytes(32));"</code>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_staff_login();
|
||||
header('Content-Type: application/json');
|
||||
$n = trim($_GET['n'] ?? '');
|
||||
$stmt = get_db()->prepare('SELECT id, subject, department_id FROM tickets WHERE ticket_number = ?');
|
||||
$stmt->execute([$n]);
|
||||
$t = $stmt->fetch();
|
||||
if ($t && !staff_can_access_department($staff, (int) $t['department_id'])) $t = false; // Betreff fremder Abteilungen nicht preisgeben
|
||||
echo json_encode($t ? ['id' => $t['id'], 'subject' => $t['subject']] : ['id' => null]);
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
/**
|
||||
* staff/_tickets_list_partial.php
|
||||
*
|
||||
* Rendert NUR die Ticket-Tabelle (inkl. "X Treffer"-Banner und Pagination), ohne
|
||||
* Kopf/Filterleiste/Fußzeile. Wird von staff/tickets.php an zwei Stellen genutzt:
|
||||
* 1) normal eingebunden beim vollständigen Seitenaufbau
|
||||
* 2) bei ?partial=1 als einziger Output für den Live-Refresh per JS (siehe
|
||||
* dortiges <script> weiter unten in tickets.php) – damit die Tabelle alle paar
|
||||
* Sekunden ohne Seiten-Reload aktuell bleibt, auch während ein Mitarbeiter
|
||||
* gerade auf der Liste ist.
|
||||
* Erwartet dieselben Variablen, die tickets.php vor dem Einbinden bereits berechnet
|
||||
* hat ($tickets, $ticketTags, $totalPages, $page, $totalCount, $departments, $search,
|
||||
* $filterDept/$filterStatus/... sowie $_GET für die Pagination-Links).
|
||||
*/
|
||||
?>
|
||||
<div id="tickets-live-region">
|
||||
<form method="post" id="bulk-form-tickets">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="bulk_action" id="bulk_action_tickets" value="">
|
||||
|
||||
<div class="card">
|
||||
<?php if ($search || $filterDept || ($filterStatus && $filterStatus !== '') || $filterPrio || $filterAssign || $filterTag || $filterSpam): ?>
|
||||
<div style="padding:8px 12px; margin-bottom:12px; background:var(--primary-lt); border-radius:6px; font-size:.84rem; color:var(--primary-dk); font-weight:500">
|
||||
<?= count($tickets) ?> Treffer
|
||||
<?php if ($search): ?> für „<?= e($search) ?>"<?php endif; ?>
|
||||
<?php if ($filterDept): ?> · Abteilung: <?= e(array_column($departments, 'name', 'id')[$filterDept] ?? '') ?><?php endif; ?>
|
||||
· <a href="/staff/tickets.php" style="color:var(--primary-dk)">Filter zurücksetzen</a>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php if (!$tickets): ?>
|
||||
<div class="empty-state">Keine Tickets gefunden.</div>
|
||||
<?php else: ?>
|
||||
<table>
|
||||
<thead><tr>
|
||||
<th style="width:24px"><input type="checkbox" onclick="document.querySelectorAll('.ticket-check').forEach(c=>c.checked=this.checked)"></th>
|
||||
<th>Ticket</th><th>Betreff</th><th>Abteilung</th><th>Priorität</th><th>Status</th><th>Zugewiesen</th><th>Fällig</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($tickets as $t):
|
||||
[$label, $color] = status_label($t['status']);
|
||||
$isOverdue = $t['resolution_due_at'] && strtotime($t['resolution_due_at']) < time() && !in_array($t['status'], ['resolved','closed']);
|
||||
?>
|
||||
<tr class="<?= $isOverdue ? 'is-overdue' : '' ?>">
|
||||
<td><input type="checkbox" class="ticket-check" name="ticket_ids[]" value="<?= $t['id'] ?>"></td>
|
||||
<td><a href="/staff/ticket_view.php?n=<?= urlencode($t['ticket_number']) ?>" class="ticket-no">#<?= e($t['ticket_number']) ?></a></td>
|
||||
<td><a href="/staff/ticket_view.php?n=<?= urlencode($t['ticket_number']) ?>"><?= e($t['subject']) ?></a><br>
|
||||
<span class="muted" style="font-size:.78rem"><?= e($t['requester_name']) ?></span>
|
||||
<span class="muted" style="font-size:.75rem; color:var(--muted-lt)"> · <?= e($t['requester_email']) ?></span>
|
||||
<?php if (!empty($ticketTags[$t['id']])): ?>
|
||||
<div style="margin-top:4px">
|
||||
<?php foreach ($ticketTags[$t['id']] as $tg): ?>
|
||||
<span class="badge" style="background:<?= e($tg['color']) ?>; font-size:.7rem"><?= e($tg['name']) ?></span>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td><?= e($t['department_name']) ?></td>
|
||||
<td><span class="badge" style="background:<?= e($t['priority_color']) ?>"><?= e($t['priority_name']) ?></span></td>
|
||||
<td><span class="badge" style="background:<?= $color ?>"><?= e($label) ?></span></td>
|
||||
<td><?= $t['staff_name'] ? e($t['staff_name']) : '<span class="muted">–</span>' ?></td>
|
||||
<td class="muted"><?= time_until($t['resolution_due_at']) ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<?php if ($totalPages > 1): ?>
|
||||
<div style="display:flex;justify-content:center;align-items:center;gap:6px;margin-top:20px;flex-wrap:wrap">
|
||||
<?php
|
||||
$baseUrl = '/staff/tickets.php?' . http_build_query(array_diff_key($_GET, ['page'=>'','partial'=>''])) . '&page=';
|
||||
$start = max(1, $page-2);
|
||||
$end = min($totalPages, $page+2);
|
||||
?>
|
||||
<?php if ($page > 1): ?>
|
||||
<a href="<?= $baseUrl.($page-1) ?>" class="btn secondary" style="padding:6px 12px">← Zurück</a>
|
||||
<?php endif; ?>
|
||||
<?php for ($p = $start; $p <= $end; $p++): ?>
|
||||
<a href="<?= $baseUrl.$p ?>" class="btn <?= $p===$page?'':'secondary' ?>" style="padding:6px 12px;<?= $p===$page?'font-weight:700':'' ?>"><?= $p ?></a>
|
||||
<?php endfor; ?>
|
||||
<?php if ($page < $totalPages): ?>
|
||||
<a href="<?= $baseUrl.($page+1) ?>" class="btn secondary" style="padding:6px 12px">Weiter →</a>
|
||||
<?php endif; ?>
|
||||
<span class="muted" style="font-size:.82rem"><?= number_format($totalCount) ?> Tickets gesamt</span>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
/**
|
||||
* Gemeinsame UI-Bausteine für die Verwaltungsseiten im osTicket-Stil
|
||||
* (Liste mit Spalten, danach ein Formular mit Reitern).
|
||||
*/
|
||||
|
||||
/** CSS + JS für Reiter. $startTab = data-tab des zuerst gezeigten Reiters. */
|
||||
function ui_tab_assets(string $startTab): void
|
||||
{
|
||||
?>
|
||||
<style>
|
||||
.tab-btn{background:none;border:1px solid transparent;border-bottom:none;padding:8px 16px;cursor:pointer;border-radius:6px 6px 0 0;color:var(--muted)}
|
||||
.tab-btn.active{background:var(--card-bg,#fff);border-color:var(--border);color:inherit;font-weight:600;position:relative;top:1px}
|
||||
</style>
|
||||
<script>
|
||||
(function () {
|
||||
var btns = document.querySelectorAll('.tab-btn'), panes = document.querySelectorAll('.tab-pane');
|
||||
function show(t) {
|
||||
btns.forEach(function (b) { b.classList.toggle('active', b.dataset.tab === t); });
|
||||
panes.forEach(function (p) { p.style.display = p.dataset.pane === t ? '' : 'none'; });
|
||||
}
|
||||
btns.forEach(function (b) { b.addEventListener('click', function () { show(b.dataset.tab); }); });
|
||||
show(<?= json_encode($startTab) ?>);
|
||||
})();
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
/** Reiterleiste: $tabs = ['key' => 'Beschriftung', …] */
|
||||
function ui_tab_bar(array $tabs): void
|
||||
{
|
||||
echo '<div style="display:flex;gap:4px;padding:10px 12px 0;border-bottom:1px solid var(--border)">';
|
||||
foreach ($tabs as $key => $label) {
|
||||
echo '<button type="button" class="tab-btn" data-tab="' . e($key) . '">' . e($label) . '</button>';
|
||||
}
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
/** Status-Auswahl (Aktiv/Deaktiviert) als Radio-Buttons; Feldname "status" mit den Werten active|inactive. */
|
||||
function ui_status_radios(bool $active, string $inactiveLabel = 'Deaktiviert'): void
|
||||
{
|
||||
echo '<label>Status *</label><div style="display:flex;gap:18px;margin:4px 0 10px">';
|
||||
echo '<label style="display:flex;align-items:center;gap:6px;margin:0"><input type="radio" name="status" value="active" style="width:auto"' . ($active ? ' checked' : '') . '> <strong>Aktiv</strong></label>';
|
||||
echo '<label style="display:flex;align-items:center;gap:6px;margin:0"><input type="radio" name="status" value="inactive" style="width:auto"' . ($active ? '' : ' checked') . '> ' . e($inactiveLabel) . '</label>';
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
/** Datum für Listenspalten ("–" bei leer). */
|
||||
function ui_date(?string $dt): string
|
||||
{
|
||||
return $dt ? date('d.m.Y H:i', strtotime($dt)) : '–';
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_staff_login();
|
||||
$pdo = get_db();
|
||||
|
||||
$errors = [];
|
||||
$allStaff = $pdo->query('SELECT id, name FROM staff WHERE is_active = 1 ORDER BY name')->fetchAll();
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
verify_csrf();
|
||||
$action = $_POST['action'] ?? '';
|
||||
|
||||
if ($action === 'create') {
|
||||
$title = trim($_POST['title'] ?? '');
|
||||
$desc = trim($_POST['description'] ?? '');
|
||||
$assignTo = ($_POST['assigned_to'] ?? '') !== '' ? (int)$_POST['assigned_to'] : null;
|
||||
$dueAt = trim($_POST['due_at'] ?? '') ?: null;
|
||||
$ticketId = ($_POST['ticket_id'] ?? '') !== '' ? (int)$_POST['ticket_id'] : null;
|
||||
|
||||
if ($title === '') $errors[] = 'Bitte einen Titel angeben.';
|
||||
if (!$errors) {
|
||||
$pdo->prepare('INSERT INTO tasks (ticket_id,title,description,assigned_to,due_at,created_by,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)')
|
||||
->execute([$ticketId, $title, $desc ?: null, $assignTo, $dueAt, $staff['id'], db_now(), db_now()]);
|
||||
flash('success', 'Aufgabe erstellt.');
|
||||
if ($ticketId) {
|
||||
$tn = $pdo->prepare('SELECT ticket_number FROM tickets WHERE id=?'); $tn->execute([$ticketId]);
|
||||
redirect('/staff/ticket_view.php?n=' . urlencode($tn->fetchColumn()));
|
||||
}
|
||||
redirect('/staff/tasks.php');
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'update_status') {
|
||||
$id = (int) $_POST['id'];
|
||||
$status = in_array($_POST['status']??'', ['open','in_progress','done']) ? $_POST['status'] : 'open';
|
||||
$pdo->prepare('UPDATE tasks SET status=?, updated_at=? WHERE id=?')->execute([$status, db_now(), $id]);
|
||||
// Kein open redirect: Referer nur wenn er auf /staff/ zeigt
|
||||
$ref = $_SERVER['HTTP_REFERER'] ?? '';
|
||||
$safePath = (parse_url($ref, PHP_URL_HOST) === ($_SERVER['HTTP_HOST'] ?? '') && strpos(parse_url($ref, PHP_URL_PATH) ?? '', '/staff/') === 0)
|
||||
? $ref : '/staff/tasks.php';
|
||||
redirect($safePath);
|
||||
}
|
||||
|
||||
if ($action === 'delete') {
|
||||
$pdo->prepare('DELETE FROM tasks WHERE id=?')->execute([(int)$_POST['id']]);
|
||||
flash('success', 'Aufgabe gelöscht.');
|
||||
redirect('/staff/tasks.php');
|
||||
}
|
||||
}
|
||||
|
||||
$filter = $_GET['filter'] ?? 'my'; // my, all, open, done
|
||||
$where = [];
|
||||
$params = [];
|
||||
|
||||
if ($filter === 'my') {
|
||||
$where[] = 'ta.assigned_to = ?'; $params[] = $staff['id'];
|
||||
} elseif ($filter === 'open') {
|
||||
$where[] = "ta.status != 'done'";
|
||||
} elseif ($filter === 'done') {
|
||||
$where[] = "ta.status = 'done'";
|
||||
}
|
||||
|
||||
$sql = 'SELECT ta.*, s.name AS assigned_name, s2.name AS creator_name,
|
||||
t.ticket_number, t.subject AS ticket_subject
|
||||
FROM tasks ta
|
||||
LEFT JOIN staff s ON s.id = ta.assigned_to
|
||||
LEFT JOIN staff s2 ON s2.id = ta.created_by
|
||||
LEFT JOIN tickets t ON t.id = ta.ticket_id'
|
||||
. ($where ? ' WHERE ' . implode(' AND ', $where) : '')
|
||||
. ' ORDER BY ta.due_at IS NULL, ta.due_at ASC, ta.created_at DESC LIMIT 200';
|
||||
$stmt = $pdo->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$tasks = $stmt->fetchAll();
|
||||
|
||||
$statusLabels = ['open'=>'Offen','in_progress'=>'In Arbeit','done'=>'Erledigt'];
|
||||
$statusColors = ['open'=>'#2563eb','in_progress'=>'#d97706','done'=>'#16a34a'];
|
||||
|
||||
$pageTitle = 'Aufgaben'; $activePage = 'tasks';
|
||||
require __DIR__ . '/_header.php';
|
||||
?>
|
||||
<div class="topbar">
|
||||
<h1>Aufgaben</h1>
|
||||
<button type="button" class="btn" onclick="document.getElementById('new-task-form').style.display=document.getElementById('new-task-form').style.display==='none'?'':'none'">+ Neue Aufgabe</button>
|
||||
</div>
|
||||
|
||||
<?php foreach ($errors as $e): ?><div class="flash error"><?= e($e) ?></div><?php endforeach; ?>
|
||||
|
||||
<!-- Neue Aufgabe -->
|
||||
<div id="new-task-form" class="card" style="display:none; margin-bottom:20px">
|
||||
<h3>Neue Aufgabe</h3>
|
||||
<form method="post">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="create">
|
||||
<div class="field-row">
|
||||
<div style="flex:2">
|
||||
<label for="title">Titel <span style="color:var(--danger)">*</span></label>
|
||||
<input type="text" id="title" name="title" placeholder="Was ist zu tun?" required>
|
||||
</div>
|
||||
<div>
|
||||
<label for="due_at">Fällig bis</label>
|
||||
<input type="datetime-local" id="due_at" name="due_at">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field-row">
|
||||
<div>
|
||||
<label for="assigned_to">Zuweisen an</label>
|
||||
<select name="assigned_to" id="assigned_to">
|
||||
<option value="<?= $staff['id'] ?>" selected><?= e($staff['name']) ?> (ich)</option>
|
||||
<?php foreach ($allStaff as $s): if ($s['id'] == $staff['id']) continue; ?>
|
||||
<option value="<?= $s['id'] ?>"><?= e($s['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label for="ticket_id_text">Ticket verknüpfen (Ticket-Nr., optional)</label>
|
||||
<input type="text" id="ticket_id_text" placeholder="z.B. 260622-1234" oninput="lookupTicket(this.value)">
|
||||
<input type="hidden" name="ticket_id" id="ticket_id_hidden">
|
||||
<div id="ticket_lookup_result" style="font-size:.78rem; color:var(--muted); margin-top:2px"></div>
|
||||
</div>
|
||||
</div>
|
||||
<label for="description">Beschreibung (optional)</label>
|
||||
<textarea id="description" name="description" style="min-height:80px"></textarea>
|
||||
<div class="btn-row">
|
||||
<button type="submit" class="btn">Erstellen</button>
|
||||
<button type="button" class="btn secondary" onclick="document.getElementById('new-task-form').style.display='none'">Abbrechen</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Filter-Tabs -->
|
||||
<div style="display:flex; gap:0; border-bottom:2px solid var(--border); margin-bottom:16px">
|
||||
<?php foreach (['my'=>'Meine','all'=>'Alle','open'=>'Offen','done'=>'Erledigt'] as $f=>$lbl): ?>
|
||||
<a href="/staff/tasks.php?filter=<?= $f ?>"
|
||||
style="padding:8px 18px; font-size:.88rem; font-weight:600; text-decoration:none; border-bottom:3px solid <?= $filter===$f?'var(--primary)':'transparent' ?>; margin-bottom:-2px; color:<?= $filter===$f?'var(--primary)':'var(--muted)' ?>">
|
||||
<?= $lbl ?>
|
||||
</a>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<table>
|
||||
<thead><tr><th>Aufgabe</th><th>Verknüpftes Ticket</th><th>Zugewiesen</th><th>Fällig</th><th>Status</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($tasks as $task):
|
||||
$overdue = $task['due_at'] && $task['status'] !== 'done' && strtotime($task['due_at']) < time();
|
||||
?>
|
||||
<tr class="<?= $overdue ? 'is-overdue' : '' ?>">
|
||||
<td>
|
||||
<strong style="<?= $task['status']==='done' ? 'text-decoration:line-through;color:var(--muted)' : '' ?>"><?= e($task['title']) ?></strong>
|
||||
<?php if ($task['description']): ?><br><span class="muted" style="font-size:.78rem"><?= e(mb_strimwidth($task['description'], 0, 80, '…')) ?></span><?php endif; ?>
|
||||
</td>
|
||||
<td>
|
||||
<?php if ($task['ticket_number']): ?>
|
||||
<a href="/staff/ticket_view.php?n=<?= e($task['ticket_number']) ?>" class="ticket-no">#<?= e($task['ticket_number']) ?></a><br>
|
||||
<span class="muted" style="font-size:.76rem"><?= e(mb_strimwidth($task['ticket_subject']??'', 0, 40, '…')) ?></span>
|
||||
<?php else: ?><span class="muted">–</span><?php endif; ?>
|
||||
</td>
|
||||
<td><?= e($task['assigned_name'] ?? '–') ?></td>
|
||||
<td class="muted" style="white-space:nowrap; <?= $overdue ? 'color:var(--danger)' : '' ?>">
|
||||
<?= $task['due_at'] ? format_dt($task['due_at']) : '–' ?>
|
||||
</td>
|
||||
<td>
|
||||
<form method="post" style="display:inline">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="update_status">
|
||||
<input type="hidden" name="id" value="<?= $task['id'] ?>">
|
||||
<select name="status" onchange="this.form.submit()" style="padding:3px 6px; font-size:.78rem; border-radius:5px">
|
||||
<?php foreach ($statusLabels as $sv=>$sl): ?>
|
||||
<option value="<?= $sv ?>" <?= $task['status']===$sv?'selected':'' ?>><?= $sl ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<form method="post" style="display:inline" onsubmit="return confirm('Aufgabe löschen?')">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="delete">
|
||||
<input type="hidden" name="id" value="<?= $task['id'] ?>">
|
||||
<button type="submit" style="background:none;border:none;color:#dc2626;cursor:pointer;padding:0;font-size:.85rem">✕</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php if (!$tasks): ?><tr><td colspan="6" class="muted" style="text-align:center;padding:28px">Keine Aufgaben gefunden.</td></tr><?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function lookupTicket(num) {
|
||||
var n = num.trim();
|
||||
var hidden = document.getElementById('ticket_id_hidden');
|
||||
var result = document.getElementById('ticket_lookup_result');
|
||||
if (!n) { hidden.value=''; result.textContent=''; return; }
|
||||
fetch('/staff/_ticket_lookup_ajax.php?n=' + encodeURIComponent(n))
|
||||
.then(r=>r.json()).then(d=>{
|
||||
if (d.id) { hidden.value=d.id; result.textContent='✓ ' + d.subject; result.style.color='var(--success)'; }
|
||||
else { hidden.value=''; result.textContent='Ticket nicht gefunden'; result.style.color='var(--danger)'; }
|
||||
}).catch(()=>{hidden.value='';result.textContent='';});
|
||||
}
|
||||
</script>
|
||||
<?php require __DIR__ . '/_footer.php'; ?>
|
||||
@@ -0,0 +1,180 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_admin_or_permission('manage_teams');
|
||||
$pdo = get_db();
|
||||
|
||||
$errors = [];
|
||||
$allStaff = $pdo->query('SELECT id, name FROM staff WHERE is_active = 1 ORDER BY name')->fetchAll();
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
verify_csrf();
|
||||
$action = $_POST['action'] ?? '';
|
||||
|
||||
if ($action === 'create' || $action === 'update') {
|
||||
$id = $action === 'update' ? (int) ($_POST['id'] ?? 0) : 0;
|
||||
try {
|
||||
team_save($pdo, $id, [
|
||||
'name' => $_POST['name'] ?? '', 'lead_id' => $_POST['lead_id'] ?? null, 'notes' => $_POST['notes'] ?? '',
|
||||
'is_active' => ($_POST['status'] ?? 'active') === 'active', 'no_alerts' => !empty($_POST['no_alerts']),
|
||||
'members' => $_POST['members'] ?? [],
|
||||
]);
|
||||
audit_log($staff['id'], ($action === 'create' ? 'Team erstellt: ' : 'Team aktualisiert: ') . trim($_POST['name'] ?? ''));
|
||||
flash('success', $action === 'create' ? 'Team erstellt.' : 'Änderungen gespeichert.');
|
||||
redirect('/staff/teams.php');
|
||||
} catch (AdminModelException $e) {
|
||||
$errors[] = $e->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'delete') {
|
||||
$deleted = team_delete($pdo, (int) $_POST['id']);
|
||||
audit_log($staff['id'], "Team gelöscht: {$deleted}");
|
||||
flash('success', 'Team gelöscht.');
|
||||
redirect('/staff/teams.php');
|
||||
}
|
||||
}
|
||||
|
||||
$isNew = isset($_GET['new']);
|
||||
$editId = (int) ($_GET['edit'] ?? 0);
|
||||
$showForm = $isNew || $editId || ($errors && in_array($_POST['action'] ?? '', ['create', 'update'], true));
|
||||
|
||||
$editTeam = null; $editMembers = [];
|
||||
if ($editId) {
|
||||
$es = $pdo->prepare('SELECT * FROM teams WHERE id = ?'); $es->execute([$editId]);
|
||||
$editTeam = $es->fetch() ?: null;
|
||||
$em = $pdo->prepare('SELECT staff_id FROM team_members WHERE team_id = ?'); $em->execute([$editId]);
|
||||
$editMembers = array_map('intval', $em->fetchAll(PDO::FETCH_COLUMN));
|
||||
}
|
||||
if ($_POST && $errors) $editMembers = array_map('intval', (array) ($_POST['members'] ?? []));
|
||||
|
||||
$teams = $pdo->query(
|
||||
'SELECT t.*, s.name AS lead_name,
|
||||
(SELECT COUNT(*) FROM team_members tm WHERE tm.team_id = t.id) AS member_count
|
||||
FROM teams t LEFT JOIN staff s ON s.id = t.lead_id ORDER BY t.name'
|
||||
)->fetchAll();
|
||||
$fmt = fn(?string $dt) => $dt ? date('d.m.Y H:i', strtotime($dt)) : '–';
|
||||
|
||||
$pageTitle = 'Teams'; $activePage = 'teams';
|
||||
require __DIR__ . '/_header.php';
|
||||
?>
|
||||
|
||||
<?php foreach ($errors as $err): ?><div class="flash error"><?= e($err) ?></div><?php endforeach; ?>
|
||||
|
||||
<?php if ($showForm): ?>
|
||||
<?php
|
||||
$f = fn(string $k, $default = '') => $_POST[$k] ?? $default;
|
||||
$v = fn(string $k, string $col, $default = '') => $f($k, $editTeam[$col] ?? $default);
|
||||
$curStatus = $_POST ? ($_POST['status'] ?? 'active') : (($editTeam['is_active'] ?? 1) ? 'active' : 'inactive');
|
||||
$curLead = (string) $v('lead_id', 'lead_id');
|
||||
$noAlerts = $_POST ? !empty($_POST['no_alerts']) : !empty($editTeam['no_alerts']);
|
||||
?>
|
||||
<h1>
|
||||
<?= $editTeam ? 'Team aktualisieren' : 'Neues Team' ?>
|
||||
<?php if ($editTeam): ?><span class="muted" style="font-size:1rem;font-weight:400">— <?= e($editTeam['name']) ?></span><?php endif; ?>
|
||||
</h1>
|
||||
|
||||
<form method="post" class="card" style="padding:0">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="<?= $editTeam ? 'update' : 'create' ?>">
|
||||
<?php if ($editTeam): ?><input type="hidden" name="id" value="<?= (int) $editTeam['id'] ?>"><?php endif; ?>
|
||||
|
||||
<div style="display:flex;gap:4px;padding:10px 12px 0;border-bottom:1px solid var(--border)">
|
||||
<button type="button" class="tab-btn" data-tab="team">Team</button>
|
||||
<button type="button" class="tab-btn" data-tab="members">Mitglieder (<?= count($editMembers) ?>)</button>
|
||||
</div>
|
||||
|
||||
<div class="tab-pane" data-pane="team" style="padding:16px 20px">
|
||||
<h3 style="margin-top:0">Teaminformationen</h3>
|
||||
<label for="name">Name *</label>
|
||||
<input type="text" id="name" name="name" value="<?= e($v('name', 'name')) ?>" required>
|
||||
<label>Status *</label>
|
||||
<div style="display:flex;gap:18px;margin:4px 0 10px">
|
||||
<label style="display:flex;align-items:center;gap:6px;margin:0"><input type="radio" name="status" value="active" style="width:auto" <?= $curStatus === 'active' ? 'checked' : '' ?>> <strong>Aktiv</strong></label>
|
||||
<label style="display:flex;align-items:center;gap:6px;margin:0"><input type="radio" name="status" value="inactive" style="width:auto" <?= $curStatus !== 'active' ? 'checked' : '' ?>> Deaktiviert</label>
|
||||
</div>
|
||||
<label for="lead_id">Teamleiter</label>
|
||||
<select name="lead_id" id="lead_id" style="max-width:320px">
|
||||
<option value="">— Keine(r) —</option>
|
||||
<?php foreach ($allStaff as $s): ?>
|
||||
<option value="<?= $s['id'] ?>" <?= $curLead === (string) $s['id'] ? 'selected' : '' ?>><?= e($s['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<label style="display:flex;align-items:center;gap:8px;margin-top:14px">
|
||||
<input type="checkbox" name="no_alerts" style="width:auto" <?= $noAlerts ? 'checked' : '' ?>>
|
||||
Benachrichtigung bei Ticketzuweisung für dieses Team <strong>deaktivieren</strong>
|
||||
</label>
|
||||
<h3>Administratornotizen <span class="muted" style="font-weight:400;font-size:.85rem">– Interne Notizen, sichtbar für alle Administratoren</span></h3>
|
||||
<textarea id="notes" name="notes" rows="6"><?= e($v('notes', 'notes')) ?></textarea>
|
||||
</div>
|
||||
|
||||
<div class="tab-pane" data-pane="members" style="padding:16px 20px;display:none">
|
||||
<h3 style="margin-top:0">Mitglieder</h3>
|
||||
<?php if (!$allStaff): ?>
|
||||
<p class="muted">Es gibt keine aktiven Mitarbeiter.</p>
|
||||
<?php else: foreach ($allStaff as $s): ?>
|
||||
<label style="display:flex;align-items:center;gap:8px;padding:4px 0;font-weight:400;cursor:pointer">
|
||||
<input type="checkbox" name="members[]" value="<?= $s['id'] ?>" style="width:auto" <?= in_array((int) $s['id'], $editMembers, true) ? 'checked' : '' ?>>
|
||||
<?= e($s['name']) ?>
|
||||
</label>
|
||||
<?php endforeach; endif; ?>
|
||||
</div>
|
||||
|
||||
<div class="btn-row" style="padding:0 20px 18px">
|
||||
<button type="submit" class="btn"><?= $editTeam ? 'Änderungen speichern' : 'Erstellen' ?></button>
|
||||
<a href="/staff/teams.php" class="btn secondary">Abbrechen</a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<style>
|
||||
.tab-btn{background:none;border:1px solid transparent;border-bottom:none;padding:8px 16px;cursor:pointer;border-radius:6px 6px 0 0;color:var(--muted)}
|
||||
.tab-btn.active{background:var(--card-bg,#fff);border-color:var(--border);color:inherit;font-weight:600;position:relative;top:1px}
|
||||
</style>
|
||||
<script>
|
||||
(function () {
|
||||
var btns = document.querySelectorAll('.tab-btn'), panes = document.querySelectorAll('.tab-pane');
|
||||
function show(t) {
|
||||
btns.forEach(function (b) { b.classList.toggle('active', b.dataset.tab === t); });
|
||||
panes.forEach(function (p) { p.style.display = p.dataset.pane === t ? '' : 'none'; });
|
||||
}
|
||||
btns.forEach(function (b) { b.addEventListener('click', function () { show(b.dataset.tab); }); });
|
||||
show('team');
|
||||
})();
|
||||
</script>
|
||||
|
||||
<?php else: ?>
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;gap:12px">
|
||||
<h1 style="margin:0">Teams</h1>
|
||||
<a href="/staff/teams.php?new=1" class="btn">Neues Team hinzufügen</a>
|
||||
</div>
|
||||
<p class="muted">Abteilungsübergreifende Mitarbeiter-Gruppen. Tickets können einem Team statt einem einzelnen Mitarbeiter zugewiesen werden; die Mitglieder werden dabei benachrichtigt.</p>
|
||||
|
||||
<div class="card">
|
||||
<table>
|
||||
<thead><tr><th>Teamname</th><th>Status</th><th style="text-align:center">Mitglieder</th><th>Teamleiter</th><th>Erstellt</th><th>Zuletzt aktualisiert</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($teams as $t): ?>
|
||||
<tr>
|
||||
<td><a href="/staff/teams.php?edit=<?= (int) $t['id'] ?>"><?= e($t['name']) ?></a></td>
|
||||
<td><strong><?= $t['is_active'] ? 'Aktiv' : 'Deaktiviert' ?></strong></td>
|
||||
<td style="text-align:center"><a href="/staff/teams.php?edit=<?= (int) $t['id'] ?>"><?= (int) $t['member_count'] ?></a></td>
|
||||
<td><?= e($t['lead_name'] ?? '') ?></td>
|
||||
<td class="muted" style="font-size:.82rem"><?= e($fmt($t['created_at'] ?? null)) ?></td>
|
||||
<td class="muted" style="font-size:.82rem"><?= e($fmt($t['updated_at'] ?? null)) ?></td>
|
||||
<td style="white-space:nowrap">
|
||||
<a href="/staff/teams.php?edit=<?= (int) $t['id'] ?>">Bearbeiten</a> ·
|
||||
<form method="post" style="display:inline" onsubmit="return confirm('Team wirklich löschen?')">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="delete">
|
||||
<input type="hidden" name="id" value="<?= (int) $t['id'] ?>">
|
||||
<button type="submit" style="background:none;border:none;color:#dc2626;cursor:pointer;padding:0;font-size:.9rem">Löschen</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php if (!$teams): ?><tr><td colspan="7" class="muted">Noch keine Teams angelegt.</td></tr><?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php require __DIR__ . '/_footer.php'; ?>
|
||||
@@ -0,0 +1,341 @@
|
||||
<?php
|
||||
/**
|
||||
* staff/ticket_create.php
|
||||
*
|
||||
* Ticket-Erstellung durch Mitarbeiter (z.B. Telefonanruf, Vor-Ort-Anfrage).
|
||||
* Unterschied zu ticket_new.php (Kundenportal):
|
||||
* – Kein Honeypot, kein Rate-Limit
|
||||
* – Mitarbeiter wählt Abteilung, Priorität und Hilfe-Thema direkt
|
||||
* – Kann im Namen jedes Kunden (Name + E-Mail) erstellen
|
||||
* – source = 'phone' oder 'staff'
|
||||
* – Optionale erste interne Notiz
|
||||
*/
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_staff_login();
|
||||
$pdo = get_db();
|
||||
|
||||
$myDeptIds = staff_department_ids($staff); // null = Admin (alle Abteilungen)
|
||||
|
||||
$departments = $pdo->query('SELECT * FROM departments WHERE is_active = 1 ORDER BY name')->fetchAll();
|
||||
$priorities = $pdo->query('SELECT * FROM priorities ORDER BY sort_order')->fetchAll();
|
||||
$helpTopics = help_topic_options($pdo);
|
||||
$allAgents = $pdo->query('SELECT id, name FROM staff WHERE is_active = 1 ORDER BY name')->fetchAll();
|
||||
$customFields = $pdo->query('SELECT * FROM custom_fields WHERE is_active = 1 ORDER BY sort_order, label')->fetchAll();
|
||||
|
||||
// Abteilungen auf zugängliche einschränken
|
||||
if ($myDeptIds !== null) {
|
||||
$departments = array_filter($departments, fn($d) => in_array((int) $d['id'], $myDeptIds, true));
|
||||
}
|
||||
|
||||
$errors = [];
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
verify_csrf();
|
||||
|
||||
$requesterName = trim($_POST['requester_name'] ?? '');
|
||||
$requesterEmail = trim($_POST['requester_email'] ?? '');
|
||||
$subject = trim($_POST['subject'] ?? '');
|
||||
$message = sanitize_staff_html(trim($_POST['message'] ?? ''));
|
||||
$internalNote = sanitize_staff_html(trim($_POST['internal_note'] ?? ''));
|
||||
$source = in_array($_POST['source'] ?? '', ['phone','staff','web']) ? $_POST['source'] : 'phone';
|
||||
$deptId = (int) ($_POST['department_id'] ?? ($departments[0]['id'] ?? 0));
|
||||
$prioId = (int) ($_POST['priority_id'] ?? ($priorities[0]['id'] ?? 0));
|
||||
$helpTopicId = ($_POST['help_topic_id'] ?? '') !== '' ? (int) $_POST['help_topic_id'] : null;
|
||||
$assignedId = ($_POST['assigned_staff_id'] ?? '') !== '' ? (int) $_POST['assigned_staff_id'] : null;
|
||||
|
||||
if ($requesterName === '') $errors[] = 'Bitte Name des Anfragers angeben.';
|
||||
if ($requesterEmail !== '' && !filter_var($requesterEmail, FILTER_VALIDATE_EMAIL)) {
|
||||
$errors[] = 'Bitte eine gültige E-Mail-Adresse angeben (oder das Feld leer lassen).';
|
||||
}
|
||||
if ($subject === '') $errors[] = 'Bitte einen Betreff angeben.';
|
||||
if (trim(strip_tags($message)) === '') $errors[] = 'Bitte eine Beschreibung eingeben.';
|
||||
|
||||
if (!$errors) {
|
||||
// Sperrliste prüfen (nur wenn E-Mail vorhanden)
|
||||
if ($requesterEmail !== '' && is_banned($requesterEmail)) {
|
||||
$errors[] = 'Diese E-Mail-Adresse steht auf der Sperrliste.';
|
||||
}
|
||||
}
|
||||
|
||||
if (!$errors) {
|
||||
// Ticket-Regeln anwenden
|
||||
$ruleResult = evaluate_ticket_rules($pdo, [
|
||||
'subject' => $subject,
|
||||
'message' => strip_tags($message),
|
||||
'requester_email' => $requesterEmail,
|
||||
'requester_name' => $requesterName,
|
||||
'source' => $source,
|
||||
]);
|
||||
|
||||
if ($ruleResult['set_department'] !== null) $deptId = $ruleResult['set_department'];
|
||||
if ($ruleResult['set_priority'] !== null) $prioId = $ruleResult['set_priority'];
|
||||
if ($ruleResult['set_help_topic'] !== null) $helpTopicId = $ruleResult['set_help_topic'];
|
||||
if ($ruleResult['assign_staff'] !== null && $assignedId === null) $assignedId = $ruleResult['assign_staff'];
|
||||
|
||||
$prioStmt = $pdo->prepare('SELECT * FROM priorities WHERE id = ?');
|
||||
$prioStmt->execute([$prioId]);
|
||||
$priority = $prioStmt->fetch();
|
||||
$sla = calc_sla_dates($priority, null, (int) $deptId, $helpTopicId ? (int) $helpTopicId : null);
|
||||
$now = db_now();
|
||||
$ticketNumber = generate_ticket_number($pdo);
|
||||
|
||||
// Bekannten registrierten Kunden nachschlagen
|
||||
$userId = null;
|
||||
if ($requesterEmail !== '') {
|
||||
$userStmt = $pdo->prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?)');
|
||||
$userStmt->execute([$requesterEmail]);
|
||||
$userId = $userStmt->fetchColumn() ?: null;
|
||||
}
|
||||
|
||||
$pdo->prepare(
|
||||
'INSERT INTO tickets (ticket_number, subject, user_id, requester_name, requester_email, department_id,
|
||||
help_topic_id, priority_id, status, source, assigned_staff_id,
|
||||
first_response_due_at, resolution_due_at, created_at, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
|
||||
)->execute([
|
||||
$ticketNumber, $subject, $userId, $requesterName, $requesterEmail, $deptId,
|
||||
$helpTopicId, $prioId, 'open', $source, $assignedId,
|
||||
$sla['first_response_due_at'], $sla['resolution_due_at'], $now, $now,
|
||||
]);
|
||||
$ticketId = (int) $pdo->lastInsertId();
|
||||
|
||||
// Erste Nachricht eintragen (öffentlich, vom Mitarbeiter im Namen des Kunden)
|
||||
$pdo->prepare(
|
||||
'INSERT INTO ticket_threads (ticket_id, author_type, staff_id, message, is_internal_note, created_at) VALUES (?,?,?,?,0,?)'
|
||||
)->execute([$ticketId, 'staff', $staff['id'], $message, $now]);
|
||||
|
||||
// Optionale interne Notiz
|
||||
if (trim(strip_tags($internalNote)) !== '') {
|
||||
$pdo->prepare(
|
||||
'INSERT INTO ticket_threads (ticket_id, author_type, staff_id, message, is_internal_note, created_at) VALUES (?,?,?,?,1,?)'
|
||||
)->execute([$ticketId, 'staff', $staff['id'], $internalNote, $now]);
|
||||
}
|
||||
|
||||
// Individuelle Felder
|
||||
if ($customFields) {
|
||||
$cfStmt = $pdo->prepare('INSERT INTO ticket_field_values (ticket_id, custom_field_id, value) VALUES (?,?,?)');
|
||||
foreach ($customFields as $f) {
|
||||
$fn = 'custom_' . $f['id'];
|
||||
$val = $f['field_type'] === 'checkbox' ? (!empty($_POST[$fn]) ? '1' : '0') : trim($_POST[$fn] ?? '');
|
||||
if ($val !== '' && $val !== '0') $cfStmt->execute([$ticketId, $f['id'], $val]);
|
||||
}
|
||||
}
|
||||
|
||||
log_activity($pdo, $ticketId, $staff['id'], "Ticket durch Mitarbeiter erstellt (Quelle: {$source})");
|
||||
webhook_dispatch($pdo, 'ticket.created', $ticketId);
|
||||
|
||||
foreach ($ruleResult['add_tags'] as $tagName) apply_tag_to_ticket($pdo, $ticketId, $tagName);
|
||||
if ($ruleResult['matched_rules']) {
|
||||
log_activity($pdo, $ticketId, $staff['id'], 'Ticket-Regel: ' . implode(', ', $ruleResult['matched_rules']));
|
||||
}
|
||||
|
||||
// Eingangsbestätigung an Kunden (nur wenn E-Mail vorhanden und nicht interne Quelle)
|
||||
if ($requesterEmail !== '' && !empty($_POST['notify_customer'])) {
|
||||
$deptStmt = $pdo->prepare('SELECT name, email FROM departments WHERE id = ?');
|
||||
$deptStmt->execute([$deptId]);
|
||||
$dept = $deptStmt->fetch();
|
||||
notify_customer_ticket_created([
|
||||
'ticket_number' => $ticketNumber,
|
||||
'subject' => $subject,
|
||||
'requester_name' => $requesterName,
|
||||
'requester_email' => $requesterEmail,
|
||||
'department_id' => $deptId,
|
||||
'department_name' => $dept['name'] ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
flash('success', "Ticket #{$ticketNumber} erfolgreich erstellt.");
|
||||
redirect('/staff/ticket_view.php?n=' . urlencode($ticketNumber));
|
||||
}
|
||||
}
|
||||
|
||||
$pageTitle = 'Ticket erstellen';
|
||||
$activePage = 'tickets';
|
||||
require __DIR__ . '/_header.php';
|
||||
?>
|
||||
|
||||
<div style="max-width:800px">
|
||||
|
||||
<div class="topbar">
|
||||
<h1>Neues Ticket erstellen</h1>
|
||||
<a href="/staff/tickets.php" class="btn secondary">← Zur Ticket-Liste</a>
|
||||
</div>
|
||||
<p class="muted">Ticket im Namen eines Kunden anlegen – z.B. bei Telefonanrufen oder Vor-Ort-Anfragen.</p>
|
||||
|
||||
<?php foreach ($errors as $err): ?>
|
||||
<div class="flash error"><?= e($err) ?></div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<form method="post">
|
||||
<?= csrf_field() ?>
|
||||
|
||||
<div class="card">
|
||||
<h3>Anfrage-Quelle</h3>
|
||||
<div style="display:flex; gap:10px; flex-wrap:wrap">
|
||||
<?php foreach (['phone' => '📞 Telefon', 'staff' => '🖥 Vor Ort / Intern', 'web' => '🌐 Web (im Namen)'] as $val => $lbl): ?>
|
||||
<label style="display:flex; align-items:center; gap:6px; font-weight:500; cursor:pointer; padding:9px 16px; border:2px solid var(--border); border-radius:8px; background:var(--surface); transition:.1s"
|
||||
onclick="this.parentNode.querySelectorAll('label').forEach(l=>l.style.borderColor='var(--border)'); this.style.borderColor='var(--primary)'">
|
||||
<input type="radio" name="source" value="<?= $val ?>" style="width:auto" <?= ($val==='phone')?'checked':'' ?>
|
||||
onchange="this.closest('form').querySelector('[name=source]:checked').closest('label').style.borderColor='var(--primary)'">
|
||||
<?= $lbl ?>
|
||||
</label>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3>Kundendaten</h3>
|
||||
<div class="field-row">
|
||||
<div>
|
||||
<label for="requester_name">Name <span style="color:var(--danger)">*</span></label>
|
||||
<input type="text" id="requester_name" name="requester_name"
|
||||
value="<?= e($_POST['requester_name'] ?? '') ?>"
|
||||
placeholder="Vorname Nachname" required>
|
||||
</div>
|
||||
<div>
|
||||
<label for="requester_email">E-Mail-Adresse <span class="muted" style="font-weight:400">(optional)</span></label>
|
||||
<input type="email" id="requester_email" name="requester_email"
|
||||
value="<?= e($_POST['requester_email'] ?? '') ?>"
|
||||
placeholder="kunde@beispiel.de">
|
||||
</div>
|
||||
</div>
|
||||
<label style="display:flex; align-items:center; gap:8px; margin-top:12px; font-weight:400; cursor:pointer">
|
||||
<input type="checkbox" name="notify_customer" value="1" style="width:auto" checked>
|
||||
<span>Eingangsbestätigung per E-Mail an Kunden senden (nur wenn E-Mail angegeben)</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3>Ticket-Details</h3>
|
||||
<label for="subject">Betreff <span style="color:var(--danger)">*</span></label>
|
||||
<input type="text" id="subject" name="subject"
|
||||
value="<?= e($_POST['subject'] ?? '') ?>"
|
||||
placeholder="Worum geht es?" required>
|
||||
|
||||
<div class="field-row" style="margin-top:6px">
|
||||
<div>
|
||||
<label for="department_id">Abteilung</label>
|
||||
<select name="department_id" id="department_id">
|
||||
<?php foreach ($departments as $d): ?>
|
||||
<option value="<?= $d['id'] ?>" <?= (($_POST['department_id'] ?? '') == $d['id']) ? 'selected' : '' ?>><?= e($d['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label for="priority_id">Priorität</label>
|
||||
<select name="priority_id" id="priority_id">
|
||||
<?php foreach ($priorities as $p): ?>
|
||||
<option value="<?= $p['id'] ?>" <?= (($_POST['priority_id'] ?? '') == $p['id']) ? 'selected' : '' ?>><?= e($p['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field-row">
|
||||
<?php if ($helpTopics): ?>
|
||||
<div>
|
||||
<label for="help_topic_id">Hilfe-Thema (optional)</label>
|
||||
<select name="help_topic_id" id="help_topic_id">
|
||||
<option value="">– kein Thema –</option>
|
||||
<?php foreach ($helpTopics as $t): ?>
|
||||
<option value="<?= $t['id'] ?>" <?= (($_POST['help_topic_id'] ?? '') == $t['id']) ? 'selected' : '' ?>><?= e($t['path']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<div>
|
||||
<label for="assigned_staff_id">Zuweisen an</label>
|
||||
<select name="assigned_staff_id" id="assigned_staff_id">
|
||||
<option value="">– nicht zugewiesen –</option>
|
||||
<?php foreach ($allAgents as $a): ?>
|
||||
<option value="<?= $a['id'] ?>" <?= (($_POST['assigned_staff_id'] ?? '') == $a['id'] || (!isset($_POST['assigned_staff_id']) && $a['id'] == $staff['id'])) ? 'selected' : '' ?>><?= e($a['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label for="message">Inhalt / Zusammenfassung <span style="color:var(--danger)">*</span></label>
|
||||
<div class="richtext-wrap">
|
||||
<div class="richtext-toolbar">
|
||||
<button type="button" onclick="document.execCommand('bold')"><strong>B</strong></button>
|
||||
<button type="button" onclick="document.execCommand('italic')"><em>I</em></button>
|
||||
<button type="button" onclick="document.execCommand('underline')"><u>U</u></button>
|
||||
<button type="button" onclick="document.execCommand('insertUnorderedList')">•</button>
|
||||
<button type="button" onclick="document.execCommand('insertOrderedList')">1.</button>
|
||||
</div>
|
||||
<div class="richtext-editable" id="msg-editor" contenteditable="true"><?= $_POST['message'] ?? '' ?></div>
|
||||
</div>
|
||||
<input type="hidden" name="message" id="msg-hidden">
|
||||
</div>
|
||||
|
||||
<?php if ($customFields): ?>
|
||||
<div class="card">
|
||||
<h3>Individuelle Felder</h3>
|
||||
<?php foreach ($customFields as $f):
|
||||
$fn = 'custom_' . $f['id'];
|
||||
$posted = $_POST[$fn] ?? '';
|
||||
?>
|
||||
<label for="<?= $fn ?>"><?= e($f['label']) ?><?= $f['is_required'] ? ' *' : '' ?></label>
|
||||
<?php if ($f['field_type'] === 'textarea'): ?>
|
||||
<textarea id="<?= $fn ?>" name="<?= $fn ?>" <?= $f['is_required'] ? 'required' : '' ?>><?= e($posted) ?></textarea>
|
||||
<?php elseif ($f['field_type'] === 'select'): ?>
|
||||
<select id="<?= $fn ?>" name="<?= $fn ?>" <?= $f['is_required'] ? 'required' : '' ?>>
|
||||
<option value="">– bitte wählen –</option>
|
||||
<?php foreach (preg_split('/\r?\n/', trim((string)$f['options'])) as $opt): $opt = trim($opt); if (!$opt) continue; ?>
|
||||
<option value="<?= e($opt) ?>" <?= $posted === $opt ? 'selected' : '' ?>><?= e($opt) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<?php elseif ($f['field_type'] === 'checkbox'): ?>
|
||||
<label style="display:flex; align-items:center; gap:8px; font-weight:400; margin-top:4px">
|
||||
<input type="checkbox" id="<?= $fn ?>" name="<?= $fn ?>" value="1" style="width:auto" <?= !empty($posted) ? 'checked' : '' ?>>
|
||||
<span><?= e($f['label']) ?></span>
|
||||
</label>
|
||||
<?php else: ?>
|
||||
<input type="<?= $f['field_type'] === 'number' ? 'number' : ($f['field_type'] === 'date' ? 'date' : 'text') ?>"
|
||||
id="<?= $fn ?>" name="<?= $fn ?>" value="<?= e($posted) ?>" <?= $f['is_required'] ? 'required' : '' ?>>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="card">
|
||||
<h3>Interne Notiz <span class="muted" style="font-weight:400; font-size:.85rem">(optional, nur für Mitarbeiter sichtbar)</span></h3>
|
||||
<div class="richtext-wrap">
|
||||
<div class="richtext-toolbar">
|
||||
<button type="button" onclick="document.execCommand('bold')"><strong>B</strong></button>
|
||||
<button type="button" onclick="document.execCommand('italic')"><em>I</em></button>
|
||||
<button type="button" onclick="document.execCommand('underline')"><u>U</u></button>
|
||||
<button type="button" onclick="document.execCommand('insertUnorderedList')">•</button>
|
||||
</div>
|
||||
<div class="richtext-editable" id="note-editor" contenteditable="true" style="min-height:80px; border-color:var(--accent)"><?= $_POST['internal_note'] ?? '' ?></div>
|
||||
</div>
|
||||
<input type="hidden" name="internal_note" id="note-hidden">
|
||||
</div>
|
||||
|
||||
<div class="btn-row" style="margin-bottom:40px">
|
||||
<button type="submit" class="btn" id="submit-btn">Ticket erstellen</button>
|
||||
<a href="/staff/tickets.php" class="btn secondary">Abbrechen</a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('submit-btn').closest('form').addEventListener('submit', function () {
|
||||
document.getElementById('msg-hidden').value = document.getElementById('msg-editor').innerHTML;
|
||||
document.getElementById('note-hidden').value = document.getElementById('note-editor').innerHTML;
|
||||
});
|
||||
|
||||
// Radio-Button Quell-Karten visuell updaten beim Laden
|
||||
document.querySelectorAll('input[name="source"]').forEach(function (radio) {
|
||||
radio.addEventListener('change', function () {
|
||||
document.querySelectorAll('input[name="source"]').forEach(function (r) {
|
||||
r.closest('label').style.borderColor = 'var(--border)';
|
||||
});
|
||||
this.closest('label').style.borderColor = 'var(--primary)';
|
||||
});
|
||||
if (radio.checked) radio.closest('label').style.borderColor = 'var(--primary)';
|
||||
});
|
||||
</script>
|
||||
|
||||
<?php require __DIR__ . '/_footer.php'; ?>
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
/**
|
||||
* staff/ticket_merge_search.php
|
||||
* JSON-Endpunkt für die Ticket-Zusammenführen-Suche.
|
||||
* Gibt max. 8 Tickets zurück die zur Suchanfrage passen.
|
||||
*/
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_staff_login();
|
||||
$pdo = get_db();
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
$q = trim($_GET['q'] ?? '');
|
||||
$exclude = trim($_GET['exclude'] ?? '');
|
||||
|
||||
if (strlen($q) < 2) {
|
||||
echo json_encode([]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$myDeptIds = staff_department_ids($staff);
|
||||
$like = '%' . $q . '%';
|
||||
|
||||
// Basis-Query: Ticket suchen (nicht geschlossene und nicht bereits zusammengeführte)
|
||||
$sql = "SELECT t.ticket_number, t.subject, t.requester_name, t.requester_email,
|
||||
t.status, t.created_at,
|
||||
p.name AS priority_name,
|
||||
d.name AS department_name,
|
||||
s.name AS staff_name
|
||||
FROM tickets t
|
||||
JOIN priorities p ON p.id = t.priority_id
|
||||
JOIN departments d ON d.id = t.department_id
|
||||
LEFT JOIN staff s ON s.id = t.assigned_staff_id
|
||||
WHERE t.merged_into IS NULL
|
||||
AND t.status != 'closed'
|
||||
AND (t.ticket_number LIKE ? OR t.subject LIKE ? OR t.requester_name LIKE ? OR t.requester_email LIKE ?)";
|
||||
|
||||
$params = [$like, $like, $like, $like];
|
||||
|
||||
// Ausschluss des aktuellen Tickets
|
||||
if ($exclude !== '') {
|
||||
$sql .= " AND t.ticket_number != ?";
|
||||
$params[] = $exclude;
|
||||
}
|
||||
|
||||
// Abteilungsfilter für Nicht-Admins
|
||||
if ($myDeptIds !== null) {
|
||||
$placeholders = implode(',', array_fill(0, count($myDeptIds), '?'));
|
||||
$sql .= " AND t.department_id IN ($placeholders)";
|
||||
$params = array_merge($params, $myDeptIds);
|
||||
}
|
||||
|
||||
$sql .= " ORDER BY t.updated_at DESC LIMIT 8";
|
||||
|
||||
$stmt = $pdo->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// Nur nötige Felder zurückgeben
|
||||
$out = array_map(fn($t) => [
|
||||
'ticket_number' => $t['ticket_number'],
|
||||
'subject' => $t['subject'],
|
||||
'requester_name' => $t['requester_name'],
|
||||
'requester_email' => $t['requester_email'],
|
||||
'status' => $t['status'],
|
||||
'priority_name' => $t['priority_name'],
|
||||
'department_name' => $t['department_name'],
|
||||
'staff_name' => $t['staff_name'] ?? '–',
|
||||
'created_at' => $t['created_at'],
|
||||
], $results);
|
||||
|
||||
echo json_encode($out, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG);
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_staff_login();
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
$pdo = get_db();
|
||||
$number = $_GET['n'] ?? '';
|
||||
$known = max(0, (int) ($_GET['count'] ?? 0));
|
||||
|
||||
$stmt = $pdo->prepare('SELECT id, department_id FROM tickets WHERE ticket_number = ?');
|
||||
$stmt->execute([$number]);
|
||||
$ticket = $stmt->fetch();
|
||||
|
||||
if (!$ticket || !staff_can_access_department($staff, (int) $ticket['department_id'])) {
|
||||
echo json_encode(['new_count' => $known]);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Mitarbeiter sehen auch interne Notizen
|
||||
$stmt = $pdo->prepare('SELECT COUNT(*) FROM ticket_threads WHERE ticket_id = ?');
|
||||
$stmt->execute([$ticket['id']]);
|
||||
$count = (int) $stmt->fetchColumn();
|
||||
|
||||
echo json_encode(['new_count' => $count]);
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_staff_login();
|
||||
header('Content-Type: application/json');
|
||||
|
||||
$ticketId = (int)($_GET['ticket_id'] ?? 0);
|
||||
$action = $_GET['action'] ?? 'ping';
|
||||
$pdo = get_db();
|
||||
|
||||
if (!$ticketId) { echo json_encode([]); exit; }
|
||||
|
||||
if ($action === 'leave') {
|
||||
$pdo->prepare("DELETE FROM ticket_presence WHERE ticket_id=? AND staff_id=?")
|
||||
->execute([$ticketId, $staff['id']]);
|
||||
echo json_encode(['ok' => true]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($action === 'ping') {
|
||||
// Eigene Präsenz aktualisieren
|
||||
$presenceSql = $pdo->getAttribute(PDO::ATTR_DRIVER_NAME) === 'sqlite'
|
||||
? 'INSERT INTO ticket_presence (ticket_id, staff_id, last_seen_at) VALUES (?,?,?)
|
||||
ON CONFLICT(ticket_id, staff_id) DO UPDATE SET last_seen_at=excluded.last_seen_at'
|
||||
: 'INSERT INTO ticket_presence (ticket_id, staff_id, last_seen_at) VALUES (?,?,?)
|
||||
ON DUPLICATE KEY UPDATE last_seen_at=VALUES(last_seen_at)';
|
||||
$pdo->prepare($presenceSql)->execute([$ticketId, $staff['id'], db_now()]);
|
||||
|
||||
// Alte Einträge (> 30 Sek.) löschen
|
||||
$pdo->prepare('DELETE FROM ticket_presence WHERE last_seen_at < ?')
|
||||
->execute([date('Y-m-d H:i:s', time() - 30)]);
|
||||
}
|
||||
|
||||
// Alle aktiven Mitarbeiter auf diesem Ticket zurückgeben
|
||||
$activeSince = date('Y-m-d H:i:s', time() - 30);
|
||||
$stmt = $pdo->prepare(
|
||||
"SELECT s.id, s.name, tp.last_seen_at
|
||||
FROM ticket_presence tp
|
||||
JOIN staff s ON s.id = tp.staff_id
|
||||
WHERE tp.ticket_id = ? AND tp.staff_id != ?
|
||||
AND tp.last_seen_at >= ?
|
||||
ORDER BY s.name"
|
||||
);
|
||||
$stmt->execute([$ticketId, $staff['id'], $activeSince]);
|
||||
echo json_encode($stmt->fetchAll());
|
||||
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
/**
|
||||
* staff/ticket_print.php
|
||||
* Saubere Druckansicht eines Tickets – ohne Navigation, optimiert für Druck/PDF.
|
||||
*/
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_staff_login();
|
||||
$pdo = get_db();
|
||||
|
||||
$number = $_GET['n'] ?? '';
|
||||
$stmt = $pdo->prepare(
|
||||
'SELECT t.*, p.name AS priority_name, p.color AS priority_color,
|
||||
d.name AS department_name, s.name AS staff_name
|
||||
FROM tickets t
|
||||
JOIN priorities p ON p.id = t.priority_id
|
||||
JOIN departments d ON d.id = t.department_id
|
||||
LEFT JOIN staff s ON s.id = t.assigned_staff_id
|
||||
WHERE t.ticket_number = ?'
|
||||
);
|
||||
$stmt->execute([$number]);
|
||||
$ticket = $stmt->fetch();
|
||||
|
||||
if (!$ticket) {
|
||||
http_response_code(404);
|
||||
die('Ticket nicht gefunden.');
|
||||
}
|
||||
if (!staff_can_access_department($staff, (int) $ticket['department_id'])) {
|
||||
http_response_code(403);
|
||||
die('Sie haben keinen Zugriff auf Tickets dieser Abteilung.');
|
||||
}
|
||||
|
||||
// Thread laden
|
||||
$thread = $pdo->prepare(
|
||||
'SELECT tt.*, s.name AS staff_name, u.name AS user_name
|
||||
FROM ticket_threads tt
|
||||
LEFT JOIN staff s ON s.id = tt.staff_id
|
||||
LEFT JOIN users u ON u.id = tt.user_id
|
||||
WHERE tt.ticket_id = ? AND tt.is_internal_note = 0
|
||||
ORDER BY tt.created_at ASC'
|
||||
);
|
||||
$thread->execute([$ticket['id']]);
|
||||
$messages = $thread->fetchAll();
|
||||
|
||||
// Anhänge
|
||||
$attStmt = $pdo->prepare('SELECT * FROM ticket_attachments WHERE thread_id = ?');
|
||||
|
||||
$siteName = get_setting('display_name', config()['site']['name'] ?? 'DeskHub');
|
||||
[$statusLabel] = status_label($ticket['status']);
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Ticket #<?= e($ticket['ticket_number']) ?> – <?= e($ticket['subject']) ?></title>
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 11pt; color: #1e293b; background: #fff; padding: 20mm; }
|
||||
|
||||
.print-header { display: flex; justify-content: space-between; align-items: flex-start; padding-bottom: 12px; border-bottom: 2px solid #0f6f6a; margin-bottom: 16px; }
|
||||
.print-header .logo { font-size: 18pt; font-weight: 800; color: #0f6f6a; }
|
||||
.print-header .meta { text-align: right; font-size: 9pt; color: #64748b; }
|
||||
|
||||
.ticket-title { font-size: 16pt; font-weight: 700; margin-bottom: 12px; }
|
||||
|
||||
.info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 24px; margin-bottom: 20px; padding: 12px 16px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; }
|
||||
.info-row { display: flex; gap: 8px; font-size: 9.5pt; }
|
||||
.info-label { font-weight: 600; color: #64748b; min-width: 100px; }
|
||||
.info-value { color: #1e293b; }
|
||||
|
||||
.section-title { font-size: 10pt; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; color: #64748b; margin: 20px 0 10px; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px; }
|
||||
|
||||
.message { border: 1px solid #e2e8f0; border-radius: 6px; margin-bottom: 12px; break-inside: avoid; }
|
||||
.message-header { display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; background: #f8fafc; border-bottom: 1px solid #e2e8f0; font-size: 9pt; }
|
||||
.message-header .author { font-weight: 600; }
|
||||
.message-header .date { color: #64748b; }
|
||||
.message-header.staff-header { background: #e6f4f3; }
|
||||
.message-body { padding: 10px 12px; font-size: 10pt; line-height: 1.6; }
|
||||
|
||||
.attachments { padding: 6px 12px 8px; border-top: 1px solid #e2e8f0; font-size: 9pt; color: #64748b; }
|
||||
|
||||
.print-footer { margin-top: 24px; padding-top: 10px; border-top: 1px solid #e2e8f0; font-size: 8.5pt; color: #94a3b8; display: flex; justify-content: space-between; }
|
||||
|
||||
.no-print { }
|
||||
@media print {
|
||||
body { padding: 10mm; }
|
||||
.no-print { display: none !important; }
|
||||
@page { margin: 15mm; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Drucken-Button (nur am Bildschirm) -->
|
||||
<div class="no-print" style="position:fixed;top:16px;right:16px;display:flex;gap:8px;z-index:99">
|
||||
<button onclick="window.print()" style="padding:8px 18px;background:#0f6f6a;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:.88rem;font-weight:600">🖨 Drucken / Als PDF speichern</button>
|
||||
<a href="/staff/ticket_view.php?n=<?= urlencode($number) ?>" style="padding:8px 16px;border:1px solid #e2e8f0;border-radius:6px;text-decoration:none;color:#64748b;font-size:.88rem;background:#fff">← Zurück</a>
|
||||
</div>
|
||||
|
||||
<!-- Kopfzeile -->
|
||||
<div class="print-header">
|
||||
<div class="logo"><?= e($siteName) ?></div>
|
||||
<div class="meta">
|
||||
Gedruckt: <?= date('d.m.Y H:i') ?><br>
|
||||
von: <?= e($staff['name']) ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ticket-Titel -->
|
||||
<div class="ticket-title"><?= e($ticket['subject']) ?></div>
|
||||
|
||||
<!-- Ticket-Info -->
|
||||
<div class="info-grid">
|
||||
<div class="info-row"><span class="info-label">Ticket-Nr.:</span><span class="info-value">#<?= e($ticket['ticket_number']) ?></span></div>
|
||||
<div class="info-row"><span class="info-label">Status:</span><span class="info-value"><?= e($statusLabel) ?></span></div>
|
||||
<div class="info-row"><span class="info-label">Absender:</span><span class="info-value"><?= e($ticket['requester_name']) ?> <<?= e($ticket['requester_email']) ?>></span></div>
|
||||
<div class="info-row"><span class="info-label">Priorität:</span><span class="info-value"><?= e($ticket['priority_name']) ?></span></div>
|
||||
<div class="info-row"><span class="info-label">Abteilung:</span><span class="info-value"><?= e($ticket['department_name']) ?></span></div>
|
||||
<div class="info-row"><span class="info-label">Zugewiesen:</span><span class="info-value"><?= e($ticket['staff_name'] ?? '– nicht zugewiesen –') ?></span></div>
|
||||
<div class="info-row"><span class="info-label">Erstellt:</span><span class="info-value"><?= date('d.m.Y H:i', strtotime($ticket['created_at'])) ?></span></div>
|
||||
<?php if ($ticket['resolution_due_at']): ?>
|
||||
<div class="info-row"><span class="info-label">Fällig bis:</span><span class="info-value"><?= date('d.m.Y H:i', strtotime($ticket['resolution_due_at'])) ?></span></div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<!-- Nachrichten -->
|
||||
<div class="section-title">Verlauf (<?= count($messages) ?> Nachricht<?= count($messages) !== 1 ? 'en' : '' ?>)</div>
|
||||
|
||||
<?php foreach ($messages as $msg):
|
||||
$isStaff = $msg['author_type'] === 'staff';
|
||||
$author = $isStaff ? ($msg['staff_name'] ?? 'Mitarbeiter') : ($msg['user_name'] ?? $ticket['requester_name']);
|
||||
$body = $msg['message'] ?? '';
|
||||
$isHtml = preg_match('/<[a-zA-Z][^>]*>/i', $body);
|
||||
|
||||
$attStmt->execute([$msg['id']]);
|
||||
$atts = $attStmt->fetchAll();
|
||||
?>
|
||||
<div class="message">
|
||||
<div class="message-header <?= $isStaff ? 'staff-header' : '' ?>">
|
||||
<span class="author"><?= e($author) ?><?= $isStaff ? ' (Mitarbeiter)' : ' (Kunde)' ?></span>
|
||||
<span class="date"><?= date('d.m.Y H:i', strtotime($msg['created_at'])) ?></span>
|
||||
</div>
|
||||
<div class="message-body">
|
||||
<?php if ($isHtml): ?>
|
||||
<?= sanitize_staff_html($body) ?>
|
||||
<?php else: ?>
|
||||
<?php
|
||||
$text = trim($body);
|
||||
foreach (preg_split('/\n{2,}/', $text) as $p) {
|
||||
$p = trim($p);
|
||||
if ($p !== '') echo '<p style="margin:0 0 8px">'.nl2br(e($p)).'</p>';
|
||||
}
|
||||
?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php if ($atts): ?>
|
||||
<div class="attachments">
|
||||
📎 Anhänge: <?= implode(', ', array_map(fn($a) => e($a['original_name']), $atts)) ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<!-- Fußzeile -->
|
||||
<div class="print-footer">
|
||||
<span><?= e($siteName) ?> – Ticket #<?= e($ticket['ticket_number']) ?></span>
|
||||
<span>Druckdatum: <?= date('d.m.Y H:i') ?></span>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,426 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
require_once __DIR__ . '/_ui.php';
|
||||
$staff = require_admin();
|
||||
$pdo = get_db();
|
||||
|
||||
$departments = departments_for_select($pdo, array_map('intval', $pdo->query("SELECT action_value FROM ticket_rule_actions WHERE action_type = 'set_department'")->fetchAll(PDO::FETCH_COLUMN)));
|
||||
$priorities = $pdo->query('SELECT * FROM priorities ORDER BY sort_order')->fetchAll();
|
||||
$helpTopics = $pdo->query('SELECT * FROM help_topics ORDER BY name')->fetchAll();
|
||||
$staffList = $pdo->query("SELECT id, name FROM staff WHERE is_active = 1 ORDER BY name")->fetchAll();
|
||||
$cannedResponses = $pdo->query('SELECT id, title FROM canned_responses ORDER BY title')->fetchAll();
|
||||
|
||||
$fieldLabels = [
|
||||
'subject' => 'Betreff',
|
||||
'message' => 'Nachricht',
|
||||
'requester_email' => 'Absender-E-Mail',
|
||||
'requester_name' => 'Absender-Name',
|
||||
'source' => 'Kanal (web/email)',
|
||||
];
|
||||
$operatorLabels = [
|
||||
'contains' => 'enthält',
|
||||
'not_contains' => 'enthält nicht',
|
||||
'equals' => 'ist genau',
|
||||
'starts_with' => 'beginnt mit',
|
||||
'ends_with' => 'endet mit',
|
||||
];
|
||||
$actionLabels = [
|
||||
'set_department' => 'Abteilung setzen',
|
||||
'set_priority' => 'Priorität setzen',
|
||||
'set_help_topic' => 'Hilfe-Thema setzen',
|
||||
'assign_staff' => 'Mitarbeiter zuweisen',
|
||||
'add_tag' => 'Tag hinzufügen',
|
||||
'auto_reply' => 'Auto-Antwort senden (Textbaustein)',
|
||||
'reject' => 'Ticket verwerfen (z.B. Spam)',
|
||||
];
|
||||
|
||||
$errors = [];
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
verify_csrf();
|
||||
$action = $_POST['action'] ?? '';
|
||||
|
||||
if ($action === 'create' || $action === 'update') {
|
||||
$name = trim($_POST['name'] ?? '');
|
||||
$matchType = ($_POST['match_type'] ?? 'all') === 'any' ? 'any' : 'all';
|
||||
$isActive = ($_POST['status'] ?? 'active') === 'active' ? 1 : 0;
|
||||
$notes = trim($_POST['notes'] ?? '');
|
||||
$sortOrder = (int) ($_POST['sort_order'] ?? 0);
|
||||
|
||||
$condFields = $_POST['cond_field'] ?? [];
|
||||
$condOperators = $_POST['cond_operator'] ?? [];
|
||||
$condValues = $_POST['cond_value'] ?? [];
|
||||
|
||||
$actTypes = $_POST['action_type'] ?? [];
|
||||
$actDept = $_POST['action_value_dept'] ?? [];
|
||||
$actPrio = $_POST['action_value_prio'] ?? [];
|
||||
$actTopic = $_POST['action_value_topic'] ?? [];
|
||||
$actStaff = $_POST['action_value_staff'] ?? [];
|
||||
$actTag = $_POST['action_value_tag'] ?? [];
|
||||
$actCanned = $_POST['action_value_canned'] ?? [];
|
||||
|
||||
if ($name === '') $errors[] = 'Bitte einen Namen für die Regel angeben.';
|
||||
|
||||
$conditions = [];
|
||||
foreach ($condFields as $i => $f) {
|
||||
$val = trim($condValues[$i] ?? '');
|
||||
if ($val === '') continue;
|
||||
if (!isset($fieldLabels[$f]) || !isset($operatorLabels[$condOperators[$i] ?? ''])) continue;
|
||||
$conditions[] = ['field' => $f, 'operator' => $condOperators[$i], 'value' => $val];
|
||||
}
|
||||
if (!$conditions) $errors[] = 'Bitte mindestens eine Bedingung mit einem Wert angeben.';
|
||||
|
||||
$actionsToSave = [];
|
||||
foreach ($actTypes as $i => $t) {
|
||||
if (!isset($actionLabels[$t])) continue;
|
||||
$value = match ($t) {
|
||||
'set_department' => $actDept[$i] ?? '',
|
||||
'set_priority' => $actPrio[$i] ?? '',
|
||||
'set_help_topic' => $actTopic[$i] ?? '',
|
||||
'assign_staff' => $actStaff[$i] ?? '',
|
||||
'add_tag' => trim($actTag[$i] ?? ''),
|
||||
'auto_reply' => $actCanned[$i] ?? '',
|
||||
'reject' => '1',
|
||||
default => '',
|
||||
};
|
||||
if ($t !== 'reject' && $value === '') continue;
|
||||
$actionsToSave[] = ['action_type' => $t, 'action_value' => $value];
|
||||
}
|
||||
if (!$actionsToSave) $errors[] = 'Bitte mindestens eine Aktion festlegen.';
|
||||
|
||||
if (!$errors) {
|
||||
if ($action === 'create') {
|
||||
$pdo->prepare('INSERT INTO ticket_rules (name, match_type, is_active, sort_order, notes, created_at, updated_at) VALUES (?,?,?,?,?,?,?)')
|
||||
->execute([$name, $matchType, $isActive, $sortOrder, $notes ?: null, db_now(), db_now()]);
|
||||
$ruleId = (int) $pdo->lastInsertId();
|
||||
audit_log($staff['id'], "Ticket-Regel erstellt: {$name}");
|
||||
flash('success', 'Ticket-Regel erstellt.');
|
||||
} else {
|
||||
$ruleId = (int) $_POST['id'];
|
||||
$pdo->prepare('UPDATE ticket_rules SET name=?, match_type=?, is_active=?, sort_order=?, notes=?, updated_at=? WHERE id=?')
|
||||
->execute([$name, $matchType, $isActive, $sortOrder, $notes ?: null, db_now(), $ruleId]);
|
||||
$pdo->prepare('DELETE FROM ticket_rule_conditions WHERE rule_id = ?')->execute([$ruleId]);
|
||||
$pdo->prepare('DELETE FROM ticket_rule_actions WHERE rule_id = ?')->execute([$ruleId]);
|
||||
audit_log($staff['id'], "Ticket-Regel aktualisiert: {$name}");
|
||||
flash('success', 'Ticket-Regel aktualisiert.');
|
||||
}
|
||||
$condStmt = $pdo->prepare('INSERT INTO ticket_rule_conditions (rule_id, field, operator, value) VALUES (?,?,?,?)');
|
||||
foreach ($conditions as $c) {
|
||||
$condStmt->execute([$ruleId, $c['field'], $c['operator'], $c['value']]);
|
||||
}
|
||||
$actStmt = $pdo->prepare('INSERT INTO ticket_rule_actions (rule_id, action_type, action_value) VALUES (?,?,?)');
|
||||
foreach ($actionsToSave as $a) {
|
||||
$actStmt->execute([$ruleId, $a['action_type'], $a['action_value']]);
|
||||
}
|
||||
redirect('/staff/ticket_rules.php');
|
||||
}
|
||||
}
|
||||
|
||||
if ($action === 'toggle_active') {
|
||||
$id = (int) $_POST['id'];
|
||||
$pdo->prepare('UPDATE ticket_rules SET is_active = 1 - is_active WHERE id = ?')->execute([$id]);
|
||||
redirect('/staff/ticket_rules.php');
|
||||
}
|
||||
|
||||
if ($action === 'delete') {
|
||||
$id = (int) $_POST['id'];
|
||||
$nameStmt = $pdo->prepare('SELECT name FROM ticket_rules WHERE id = ?');
|
||||
$nameStmt->execute([$id]);
|
||||
$ruleName = $nameStmt->fetchColumn();
|
||||
$pdo->prepare('DELETE FROM ticket_rules WHERE id = ?')->execute([$id]);
|
||||
audit_log($staff['id'], "Ticket-Regel gelöscht: {$ruleName}");
|
||||
flash('success', 'Ticket-Regel gelöscht.');
|
||||
redirect('/staff/ticket_rules.php');
|
||||
}
|
||||
|
||||
if ($action === 'move' && in_array($_POST['dir'] ?? '', ['up', 'down'], true)) {
|
||||
$id = (int) $_POST['id'];
|
||||
$dir = $_POST['dir'];
|
||||
$rules = $pdo->query('SELECT id, sort_order FROM ticket_rules ORDER BY sort_order, id')->fetchAll();
|
||||
$idx = null;
|
||||
foreach ($rules as $i => $r) { if ((int) $r['id'] === $id) { $idx = $i; break; } }
|
||||
$swapIdx = $dir === 'up' ? $idx - 1 : $idx + 1;
|
||||
if ($idx !== null && isset($rules[$swapIdx])) {
|
||||
$a = $rules[$idx]; $b = $rules[$swapIdx];
|
||||
$pdo->prepare('UPDATE ticket_rules SET sort_order = ? WHERE id = ?')->execute([$b['sort_order'], $a['id']]);
|
||||
$pdo->prepare('UPDATE ticket_rules SET sort_order = ? WHERE id = ?')->execute([$a['sort_order'], $b['id']]);
|
||||
}
|
||||
redirect('/staff/ticket_rules.php');
|
||||
}
|
||||
}
|
||||
|
||||
$rules = $pdo->query('SELECT * FROM ticket_rules ORDER BY sort_order, id')->fetchAll();
|
||||
foreach ($rules as &$r) {
|
||||
$cs = $pdo->prepare('SELECT * FROM ticket_rule_conditions WHERE rule_id = ?');
|
||||
$cs->execute([$r['id']]);
|
||||
$r['conditions'] = $cs->fetchAll();
|
||||
$as = $pdo->prepare('SELECT * FROM ticket_rule_actions WHERE rule_id = ?');
|
||||
$as->execute([$r['id']]);
|
||||
$r['actions'] = $as->fetchAll();
|
||||
}
|
||||
unset($r);
|
||||
|
||||
$editId = $_GET['edit'] ?? null;
|
||||
$showForm = isset($_GET['new']) || $editId || ($errors && in_array($_POST['action'] ?? '', ['create', 'update'], true));
|
||||
$editRule = null;
|
||||
if ($editId) {
|
||||
foreach ($rules as $r) { if ((int) $r['id'] === (int) $editId) { $editRule = $r; break; } }
|
||||
}
|
||||
|
||||
$pageTitle = 'Ticket-Regeln';
|
||||
$activePage = 'ticket_rules';
|
||||
require __DIR__ . '/_header.php';
|
||||
|
||||
/** Rendert die Werte-Auswahl einer Aktionszeile für eine bereits gespeicherte Aktion (Bearbeiten-Modus) */
|
||||
function render_action_value_selects(array $departments, array $priorities, array $helpTopics, array $staffList, array $cannedResponses, ?array $existing = null): void
|
||||
{
|
||||
$effectiveType = $existing['action_type'] ?? 'set_department'; // Default-Auswahl des Typ-Selects
|
||||
$sel = fn($type) => ($effectiveType === $type) ? '' : 'style="display:none"';
|
||||
$val = fn($type) => ($existing && $existing['action_type'] === $type) ? $existing['action_value'] : '';
|
||||
?>
|
||||
<select name="action_value_dept[]" class="rule-val rule-val-set_department" <?= $sel('set_department') ?>>
|
||||
<option value="">– Abteilung wählen –</option>
|
||||
<?php foreach ($departments as $d): ?>
|
||||
<option value="<?= $d['id'] ?>" <?= $val('set_department') == $d['id'] ? 'selected' : '' ?>><?= e($d['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<select name="action_value_prio[]" class="rule-val rule-val-set_priority" <?= $sel('set_priority') ?>>
|
||||
<option value="">– Priorität wählen –</option>
|
||||
<?php foreach ($priorities as $p): ?>
|
||||
<option value="<?= $p['id'] ?>" <?= $val('set_priority') == $p['id'] ? 'selected' : '' ?>><?= e($p['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<select name="action_value_topic[]" class="rule-val rule-val-set_help_topic" <?= $sel('set_help_topic') ?>>
|
||||
<option value="">– Hilfe-Thema wählen –</option>
|
||||
<?php foreach ($helpTopics as $t): ?>
|
||||
<option value="<?= $t['id'] ?>" <?= $val('set_help_topic') == $t['id'] ? 'selected' : '' ?>><?= e($t['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<select name="action_value_staff[]" class="rule-val rule-val-assign_staff" <?= $sel('assign_staff') ?>>
|
||||
<option value="">– Mitarbeiter wählen –</option>
|
||||
<?php foreach ($staffList as $s): ?>
|
||||
<option value="<?= $s['id'] ?>" <?= $val('assign_staff') == $s['id'] ? 'selected' : '' ?>><?= e($s['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<input type="text" name="action_value_tag[]" class="rule-val rule-val-add_tag" placeholder="Tag-Name" value="<?= e($val('add_tag')) ?>" <?= $sel('add_tag') ?>>
|
||||
<?php if ($cannedResponses): ?>
|
||||
<select name="action_value_canned[]" class="rule-val rule-val-auto_reply" <?= $sel('auto_reply') ?>>
|
||||
<option value="">– Textbaustein wählen –</option>
|
||||
<?php foreach ($cannedResponses as $c): ?>
|
||||
<option value="<?= $c['id'] ?>" <?= $val('auto_reply') == $c['id'] ? 'selected' : '' ?>><?= e($c['title']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<?php else: ?>
|
||||
<span class="rule-val rule-val-auto_reply muted" style="<?= $sel('auto_reply') === '' ? '' : 'display:none' ?>; align-self:center; font-size:.85rem">Noch keine Textbausteine angelegt – <a href="/staff/canned_responses.php">jetzt erstellen</a>.</span>
|
||||
<?php endif; ?>
|
||||
<span class="rule-val rule-val-reject muted" style="<?= $sel('reject') === '' ? '' : 'display:none' ?>; align-self:center; font-size:.85rem">Keine weitere Einstellung nötig.</span>
|
||||
<?php
|
||||
}
|
||||
?>
|
||||
|
||||
<?php if (!$showForm): ?>
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;gap:12px">
|
||||
<h1 style="margin:0">Ticket-Regeln (Filter)</h1>
|
||||
<a href="/staff/ticket_rules.php?new=1" class="btn">Neue Regel hinzufügen</a>
|
||||
</div>
|
||||
<p class="muted">Automatische Aktionen für neue Tickets (Web-Formular und E-Mail-Eingang), ausgewertet in der Reihenfolge unten. Trifft eine Regel mit Aktion „Ticket verwerfen“ zu, werden keine weiteren Regeln mehr geprüft.</p>
|
||||
|
||||
<?php endif; ?>
|
||||
<?php foreach ($errors as $err): ?>
|
||||
<div class="flash error"><?= e($err) ?></div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<?php if (!$showForm): ?>
|
||||
<div class="card">
|
||||
<table>
|
||||
<thead><tr><th>Reihenfolge</th><th>Name</th><th>Bedingungen</th><th>Aktionen</th><th>Status</th><th>Zuletzt aktualisiert</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($rules as $i => $r): ?>
|
||||
<tr>
|
||||
<td style="white-space:nowrap">
|
||||
<form method="post" style="display:inline">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="move"><input type="hidden" name="dir" value="up"><input type="hidden" name="id" value="<?= $r['id'] ?>">
|
||||
<button type="submit" style="background:none;border:none;cursor:pointer;padding:0 4px" <?= $i===0?'disabled':'' ?>>▲</button>
|
||||
</form>
|
||||
<form method="post" style="display:inline">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="move"><input type="hidden" name="dir" value="down"><input type="hidden" name="id" value="<?= $r['id'] ?>">
|
||||
<button type="submit" style="background:none;border:none;cursor:pointer;padding:0 4px" <?= $i===count($rules)-1?'disabled':'' ?>>▼</button>
|
||||
</form>
|
||||
</td>
|
||||
<td><a href="/staff/ticket_rules.php?edit=<?= $r['id'] ?>"><?= e($r['name']) ?></a></td>
|
||||
<td class="muted" style="font-size:.82rem">
|
||||
<?= $r['match_type']==='all' ? 'Alle:' : 'Eine von:' ?>
|
||||
<?php foreach ($r['conditions'] as $c): ?>
|
||||
<div><?= e($fieldLabels[$c['field']] ?? $c['field']) ?> <?= e($operatorLabels[$c['operator']] ?? $c['operator']) ?> „<?= e($c['value']) ?>“</div>
|
||||
<?php endforeach; ?>
|
||||
</td>
|
||||
<td class="muted" style="font-size:.82rem">
|
||||
<?php foreach ($r['actions'] as $a): ?>
|
||||
<div><?= e($actionLabels[$a['action_type']] ?? $a['action_type']) ?><?= $a['action_type']!=='reject' ? ': ' . e($a['action_value']) : '' ?></div>
|
||||
<?php endforeach; ?>
|
||||
</td>
|
||||
<td>
|
||||
<form method="post">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="toggle_active">
|
||||
<input type="hidden" name="id" value="<?= $r['id'] ?>">
|
||||
<button type="submit" class="badge" style="border:none;cursor:pointer;background:<?= $r['is_active']?'#16a34a':'#6b7280' ?>"><?= $r['is_active']?'Aktiv':'Deaktiviert' ?></button>
|
||||
</form>
|
||||
</td>
|
||||
<td class="muted" style="font-size:.82rem"><?= e(ui_date($r['updated_at'] ?? null)) ?></td>
|
||||
<td>
|
||||
<a href="/staff/ticket_rules.php?edit=<?= $r['id'] ?>">Bearbeiten</a> ·
|
||||
<form method="post" style="display:inline" onsubmit="return confirm('Regel wirklich löschen?');">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="delete">
|
||||
<input type="hidden" name="id" value="<?= $r['id'] ?>">
|
||||
<button type="submit" style="background:none;border:none;color:#dc2626;cursor:pointer;padding:0;font-size:.9rem">Löschen</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php if (!$rules): ?>
|
||||
<tr><td colspan="7" class="muted">Noch keine Ticket-Regeln angelegt.</td></tr>
|
||||
<?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<?php
|
||||
$f = fn(string $k, $default = '') => $_POST[$k] ?? $default;
|
||||
$curActive = $_POST ? (($_POST['status'] ?? 'active') === 'active') : (bool) ($editRule['is_active'] ?? 1);
|
||||
?>
|
||||
<h1>
|
||||
<?= $editRule ? 'Regel aktualisieren' : 'Neue Regel' ?>
|
||||
<?php if ($editRule): ?><span class="muted" style="font-size:1rem;font-weight:400">— <?= e($editRule['name']) ?></span><?php endif; ?>
|
||||
</h1>
|
||||
|
||||
<div class="card" id="rule-form-card" style="padding:0">
|
||||
<form method="post" id="rule-form">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="<?= $editRule ? 'update' : 'create' ?>">
|
||||
<?php if ($editRule): ?><input type="hidden" name="id" value="<?= $editRule['id'] ?>"><?php endif; ?>
|
||||
|
||||
<?php ui_tab_bar(['rule' => 'Regel', 'conds' => 'Bedingungen', 'acts' => 'Aktionen']); ?>
|
||||
|
||||
<div class="tab-pane" data-pane="rule" style="padding:16px 20px">
|
||||
<h3 style="margin-top:0">Regelinformationen</h3>
|
||||
<label for="name">Name *</label>
|
||||
<input type="text" id="name" name="name" value="<?= e($f('name', $editRule['name'] ?? '')) ?>" placeholder="z. B. Spam-Betreffzeile abweisen" required>
|
||||
<?php ui_status_radios($curActive); ?>
|
||||
<label for="sort_order">Reihenfolge</label>
|
||||
<input type="number" id="sort_order" name="sort_order" value="<?= (int) $f('sort_order', $editRule['sort_order'] ?? (count($rules) + 1) * 10) ?>" style="max-width:140px">
|
||||
<h3>Administratornotizen <span class="muted" style="font-weight:400;font-size:.85rem">– Interne Notizen, sichtbar für alle Administratoren</span></h3>
|
||||
<textarea name="notes" rows="5"><?= e($f('notes', $editRule['notes'] ?? '')) ?></textarea>
|
||||
</div>
|
||||
|
||||
<div class="tab-pane" data-pane="conds" style="padding:16px 20px;display:none">
|
||||
<label for="match_type" style="margin-top:0">Verknüpfung der Bedingungen</label>
|
||||
<select id="match_type" name="match_type" style="max-width:420px">
|
||||
<option value="all" <?= ($editRule['match_type'] ?? 'all')==='all'?'selected':'' ?>>Alle Bedingungen müssen zutreffen (UND)</option>
|
||||
<option value="any" <?= ($editRule['match_type'] ?? '')==='any'?'selected':'' ?>>Mindestens eine Bedingung muss zutreffen (ODER)</option>
|
||||
</select>
|
||||
<h4 style="margin:18px 0 8px">Bedingungen</h4>
|
||||
<div id="cond-rows">
|
||||
<?php
|
||||
$condsToRender = $editRule['conditions'] ?? [['field' => 'subject', 'operator' => 'contains', 'value' => '']];
|
||||
foreach ($condsToRender as $c):
|
||||
?>
|
||||
<div class="rule-cond-row" style="display:flex; gap:8px; margin-bottom:8px; align-items:center">
|
||||
<select name="cond_field[]" style="flex:1">
|
||||
<?php foreach ($fieldLabels as $key => $label): ?>
|
||||
<option value="<?= $key ?>" <?= ($c['field'] ?? '')===$key?'selected':'' ?>><?= e($label) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<select name="cond_operator[]" style="flex:1">
|
||||
<?php foreach ($operatorLabels as $key => $label): ?>
|
||||
<option value="<?= $key ?>" <?= ($c['operator'] ?? '')===$key?'selected':'' ?>><?= e($label) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<input type="text" name="cond_value[]" style="flex:2" placeholder="Wert" value="<?= e($c['value'] ?? '') ?>">
|
||||
<button type="button" onclick="this.closest('.rule-cond-row').remove()" style="background:none;border:none;color:#dc2626;cursor:pointer">✕</button>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<button type="button" class="btn secondary" id="add-cond-btn" style="margin-bottom:18px">+ Bedingung hinzufügen</button>
|
||||
</div>
|
||||
|
||||
<div class="tab-pane" data-pane="acts" style="padding:16px 20px;display:none">
|
||||
<h4 style="margin:0 0 8px">Aktionen</h4>
|
||||
<div id="action-rows">
|
||||
<?php
|
||||
$actionsToRender = $editRule['actions'] ?? [['action_type' => 'set_department', 'action_value' => '']];
|
||||
foreach ($actionsToRender as $a):
|
||||
?>
|
||||
<div class="rule-action-row" style="display:flex; gap:8px; margin-bottom:8px; align-items:center">
|
||||
<select name="action_type[]" class="rule-action-type" style="flex:1" onchange="updateRuleActionRow(this)">
|
||||
<?php foreach ($actionLabels as $key => $label): ?>
|
||||
<option value="<?= $key ?>" <?= ($a['action_type'] ?? '')===$key?'selected':'' ?>><?= e($label) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<div style="flex:2; display:flex">
|
||||
<?php render_action_value_selects($departments, $priorities, $helpTopics, $staffList, $cannedResponses, $a); ?>
|
||||
</div>
|
||||
<button type="button" onclick="this.closest('.rule-action-row').remove()" style="background:none;border:none;color:#dc2626;cursor:pointer">✕</button>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<button type="button" class="btn secondary" id="add-action-btn" style="margin-bottom:18px">+ Aktion hinzufügen</button>
|
||||
</div>
|
||||
|
||||
<div class="btn-row" style="padding:0 20px 18px">
|
||||
<button type="submit" class="btn"><?= $editRule ? 'Änderungen speichern' : 'Regel erstellen' ?></button>
|
||||
<a href="/staff/ticket_rules.php" class="btn secondary">Abbrechen</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<?php ui_tab_assets('rule'); ?>
|
||||
<?php endif; ?>
|
||||
|
||||
<template id="cond-row-template">
|
||||
<div class="rule-cond-row" style="display:flex; gap:8px; margin-bottom:8px; align-items:center">
|
||||
<select name="cond_field[]" style="flex:1">
|
||||
<?php foreach ($fieldLabels as $key => $label): ?><option value="<?= $key ?>"><?= e($label) ?></option><?php endforeach; ?>
|
||||
</select>
|
||||
<select name="cond_operator[]" style="flex:1">
|
||||
<?php foreach ($operatorLabels as $key => $label): ?><option value="<?= $key ?>"><?= e($label) ?></option><?php endforeach; ?>
|
||||
</select>
|
||||
<input type="text" name="cond_value[]" style="flex:2" placeholder="Wert">
|
||||
<button type="button" onclick="this.closest('.rule-cond-row').remove()" style="background:none;border:none;color:#dc2626;cursor:pointer">✕</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template id="action-row-template">
|
||||
<div class="rule-action-row" style="display:flex; gap:8px; margin-bottom:8px; align-items:center">
|
||||
<select name="action_type[]" class="rule-action-type" style="flex:1" onchange="updateRuleActionRow(this)">
|
||||
<?php foreach ($actionLabels as $key => $label): ?><option value="<?= $key ?>"><?= e($label) ?></option><?php endforeach; ?>
|
||||
</select>
|
||||
<div style="flex:2; display:flex">
|
||||
<?php render_action_value_selects($departments, $priorities, $helpTopics, $staffList, $cannedResponses, null); ?>
|
||||
</div>
|
||||
<button type="button" onclick="this.closest('.rule-action-row').remove()" style="background:none;border:none;color:#dc2626;cursor:pointer">✕</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
function updateRuleActionRow(select) {
|
||||
var row = select.closest('.rule-action-row');
|
||||
row.querySelectorAll('.rule-val').forEach(function (el) { el.style.display = 'none'; });
|
||||
var match = row.querySelector('.rule-val-' + select.value);
|
||||
if (match) match.style.display = '';
|
||||
}
|
||||
var addCond = document.getElementById('add-cond-btn');
|
||||
if (addCond) addCond.addEventListener('click', function () {
|
||||
var tpl = document.getElementById('cond-row-template');
|
||||
document.getElementById('cond-rows').appendChild(tpl.content.cloneNode(true));
|
||||
});
|
||||
var addAct = document.getElementById('add-action-btn');
|
||||
if (addAct) addAct.addEventListener('click', function () {
|
||||
var tpl = document.getElementById('action-row-template');
|
||||
document.getElementById('action-rows').appendChild(tpl.content.cloneNode(true));
|
||||
});
|
||||
</script>
|
||||
|
||||
<?php require __DIR__ . '/_footer.php'; ?>
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_staff_login();
|
||||
$pdo = get_db();
|
||||
|
||||
$ticketId = (int)($_GET['id'] ?? 0);
|
||||
if (!$ticketId) redirect('/staff/tickets.php');
|
||||
|
||||
$stmt = $pdo->prepare(
|
||||
'SELECT t.*, d.name AS department_name, p.name AS priority_name
|
||||
FROM tickets t
|
||||
JOIN departments d ON d.id = t.department_id
|
||||
JOIN priorities p ON p.id = t.priority_id
|
||||
WHERE t.id = ?'
|
||||
);
|
||||
$stmt->execute([$ticketId]);
|
||||
$ticket = $stmt->fetch();
|
||||
if (!$ticket) { http_response_code(404); die('Ticket nicht gefunden.'); }
|
||||
if (!staff_can_access_department($staff, (int) $ticket['department_id'])) { http_response_code(403); die('Sie haben keinen Zugriff auf Tickets dieser Abteilung.'); }
|
||||
|
||||
// Nachrichten laden
|
||||
$threads = $pdo->prepare(
|
||||
'SELECT tt.*, s.name AS staff_name
|
||||
FROM ticket_threads tt
|
||||
LEFT JOIN staff s ON s.id = tt.staff_id
|
||||
WHERE tt.ticket_id = ? AND tt.is_internal_note = 0
|
||||
ORDER BY tt.created_at ASC'
|
||||
);
|
||||
$threads->execute([$ticketId]);
|
||||
$messages = $threads->fetchAll();
|
||||
|
||||
$errors = [];
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
verify_csrf();
|
||||
|
||||
$selectedMsgIds = array_map('intval', $_POST['message_ids'] ?? []);
|
||||
$newSubject = trim($_POST['new_subject'] ?? '');
|
||||
|
||||
if (empty($selectedMsgIds)) {
|
||||
$errors[] = 'Bitte mindestens eine Nachricht auswählen.';
|
||||
} elseif (!$newSubject) {
|
||||
$errors[] = 'Bitte einen Betreff für das neue Ticket angeben.';
|
||||
} else {
|
||||
// Neues Ticket erstellen
|
||||
$newNumber = generate_ticket_number();
|
||||
$pdo->prepare(
|
||||
'INSERT INTO tickets (ticket_number, subject, status, priority_id, department_id,
|
||||
user_id, requester_name, requester_email, source, created_at, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?)'
|
||||
)->execute([
|
||||
$newNumber, $newSubject, 'open',
|
||||
$ticket['priority_id'], $ticket['department_id'],
|
||||
$ticket['user_id'], $ticket['requester_name'], $ticket['requester_email'],
|
||||
'staff', db_now(), db_now()
|
||||
]);
|
||||
$newId = $pdo->lastInsertId();
|
||||
|
||||
// Ausgewählte Nachrichten verschieben
|
||||
$moved = 0;
|
||||
foreach ($selectedMsgIds as $msgId) {
|
||||
$rows = $pdo->prepare('UPDATE ticket_threads SET ticket_id=? WHERE id=? AND ticket_id=?');
|
||||
$rows->execute([$newId, $msgId, $ticketId]);
|
||||
$moved += $rows->rowCount();
|
||||
}
|
||||
|
||||
// Anhänge der verschobenen Nachrichten mitnehmen
|
||||
if ($moved > 0) {
|
||||
$placeholders = implode(',', array_fill(0, count($selectedMsgIds), '?'));
|
||||
$pdo->prepare("UPDATE ticket_attachments SET ticket_id=? WHERE thread_id IN ($placeholders)")
|
||||
->execute(array_merge([$newId], $selectedMsgIds));
|
||||
}
|
||||
|
||||
// Log-Einträge
|
||||
log_activity($pdo, $ticketId, $staff['id'], "Ticket aufgeteilt → #{$newNumber} ({$moved} Nachrichten)");
|
||||
log_activity($pdo, $newId, $staff['id'], "Erstellt durch Aufteilen von #{$ticket['ticket_number']}");
|
||||
audit_log($staff['id'], "Ticket #{$ticket['ticket_number']} aufgeteilt → #{$newNumber}");
|
||||
|
||||
flash('success', "Ticket aufgeteilt. Neues Ticket: #{$newNumber}");
|
||||
redirect('/staff/ticket_view.php?n=' . urlencode($newNumber));
|
||||
}
|
||||
}
|
||||
|
||||
$pageTitle = 'Ticket aufteilen';
|
||||
$activePage = 'tickets';
|
||||
require __DIR__ . '/_header.php';
|
||||
?>
|
||||
|
||||
<div class="topbar">
|
||||
<div>
|
||||
<h1>Ticket aufteilen</h1>
|
||||
<span class="ticket-no">#<?= e($ticket['ticket_number']) ?></span>
|
||||
</div>
|
||||
<a href="/staff/ticket_view.php?n=<?= urlencode($ticket['ticket_number']) ?>" class="btn secondary">← Zurück</a>
|
||||
</div>
|
||||
|
||||
<?php foreach ($errors as $err): ?><div class="flash error"><?= e($err) ?></div><?php endforeach; ?>
|
||||
|
||||
<div style="display:grid; grid-template-columns:2fr 1fr; gap:20px; align-items:start">
|
||||
<div class="card">
|
||||
<h3>Nachrichten auswählen</h3>
|
||||
<p class="muted" style="font-size:.85rem; margin-bottom:16px">
|
||||
Wähle die Nachrichten aus die in das neue Ticket verschoben werden sollen. Die gewählten Nachrichten werden aus diesem Ticket entfernt.
|
||||
</p>
|
||||
<form method="post" id="split-form">
|
||||
<?= csrf_field() ?>
|
||||
<div style="display:flex; flex-direction:column; gap:10px; margin-bottom:20px">
|
||||
<?php foreach ($messages as $msg): ?>
|
||||
<label style="display:flex; gap:12px; padding:12px; border:1px solid var(--border); border-radius:8px; cursor:pointer; transition:background .12s"
|
||||
onmouseover="this.style.background='var(--bg-soft)'" onmouseout="this.style.background=''">
|
||||
<input type="checkbox" name="message_ids[]" value="<?= $msg['id'] ?>"
|
||||
style="width:auto; margin-top:3px; flex-shrink:0">
|
||||
<div style="min-width:0; flex:1">
|
||||
<div style="display:flex; justify-content:space-between; margin-bottom:4px">
|
||||
<strong style="font-size:.83rem"><?= e($msg['staff_name'] ?? $ticket['requester_name']) ?></strong>
|
||||
<span class="muted" style="font-size:.75rem"><?= format_dt($msg['created_at']) ?></span>
|
||||
</div>
|
||||
<div style="font-size:.85rem; color:var(--ink-soft); white-space:nowrap; overflow:hidden; text-overflow:ellipsis">
|
||||
<?= e(mb_substr(strip_tags($msg['message']), 0, 120)) ?>
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<label>Betreff des neuen Tickets</label>
|
||||
<input type="text" name="new_subject" value="<?= e('Re: '.$ticket['subject']) ?>" required>
|
||||
<div class="btn-row" style="margin-top:16px">
|
||||
<button type="submit" class="btn" onclick="return confirm('Ausgewählte Nachrichten in neues Ticket verschieben?')">
|
||||
✂️ Ticket aufteilen
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h3>Hinweise</h3>
|
||||
<ul style="padding-left:20px; line-height:2; font-size:.85rem; color:var(--muted)">
|
||||
<li>Ausgewählte Nachrichten werden in ein <strong style="color:var(--ink)">neues Ticket</strong> verschoben</li>
|
||||
<li>Anhänge der Nachrichten werden mitgenommen</li>
|
||||
<li>Das ursprüngliche Ticket bleibt mit den verbleibenden Nachrichten erhalten</li>
|
||||
<li>Beide Tickets erhalten einen Log-Eintrag</li>
|
||||
</ul>
|
||||
<div style="background:var(--bg-soft); border-radius:8px; padding:14px; margin-top:16px; font-size:.83rem">
|
||||
<div class="muted" style="margin-bottom:6px">Ursprüngliches Ticket</div>
|
||||
<strong>#<?= e($ticket['ticket_number']) ?></strong> – <?= e($ticket['subject']) ?>
|
||||
<div class="muted" style="margin-top:4px"><?= count($messages) ?> Nachrichten gesamt</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php require __DIR__ . '/_footer.php'; ?>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,634 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_staff_login();
|
||||
$pdo = get_db();
|
||||
$myDeptIds = staff_department_ids($staff); // null = Admin, alle Abteilungen
|
||||
|
||||
$departments = $pdo->query('SELECT * FROM departments ORDER BY name')->fetchAll();
|
||||
$priorities = $pdo->query('SELECT * FROM priorities ORDER BY sort_order')->fetchAll();
|
||||
$agents = $pdo->query('SELECT id, name FROM staff WHERE is_active = 1 ORDER BY name')->fetchAll();
|
||||
|
||||
$bulkErrors = [];
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// Gespeicherte Ansichten: speichern / löschen
|
||||
// ---------------------------------------------------------------
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($_POST['queue_action'] ?? '', ['save', 'delete'], true)) {
|
||||
verify_csrf();
|
||||
$back = '/staff/tickets.php' . (($_POST['return_query'] ?? '') !== '' ? '?' . ltrim((string) $_POST['return_query'], '?') : '');
|
||||
try {
|
||||
if ($_POST['queue_action'] === 'save') {
|
||||
parse_str((string) ($_POST['return_query'] ?? ''), $currentGet);
|
||||
queue_create($pdo, (int) $staff['id'], (string) ($_POST['queue_name'] ?? ''), queue_filters_from_web($currentGet), !empty($_POST['queue_shared']));
|
||||
flash('success', 'Ansicht gespeichert.');
|
||||
} else {
|
||||
$qid = (int) ($_POST['queue_id'] ?? 0);
|
||||
$row = $pdo->prepare('SELECT * FROM saved_queues WHERE id = ?');
|
||||
$row->execute([$qid]);
|
||||
$row = $row->fetch();
|
||||
if ($row && queue_can_edit($row, $staff)) {
|
||||
$pdo->prepare('DELETE FROM saved_queues WHERE id = ?')->execute([$qid]);
|
||||
flash('success', 'Ansicht gelöscht.');
|
||||
}
|
||||
$back = '/staff/tickets.php';
|
||||
}
|
||||
} catch (AdminModelException $e) {
|
||||
flash('error', $e->getMessage());
|
||||
}
|
||||
redirect($back);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// Sammelaktionen
|
||||
// ---------------------------------------------------------------
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['bulk_action'] ?? '') !== '') {
|
||||
verify_csrf();
|
||||
$ticketIds = array_filter(array_map('intval', $_POST['ticket_ids'] ?? []));
|
||||
$bulkAction = $_POST['bulk_action'];
|
||||
|
||||
if (!$ticketIds) {
|
||||
$bulkErrors[] = 'Bitte wählen Sie mindestens ein Ticket aus.';
|
||||
} else {
|
||||
// Zugriff prüfen: nur Tickets aus erlaubten Abteilungen dürfen verändert werden
|
||||
$placeholders = implode(',', array_fill(0, count($ticketIds), '?'));
|
||||
[$deptFilter, $deptParams] = dept_filter_sql($myDeptIds, 'department_id');
|
||||
$stmt = $pdo->prepare("SELECT * FROM tickets WHERE id IN ({$placeholders})" . $deptFilter);
|
||||
$stmt->execute(array_merge($ticketIds, $deptParams));
|
||||
$allowedTickets = $stmt->fetchAll();
|
||||
|
||||
if (count($allowedTickets) < count($ticketIds)) {
|
||||
$bulkErrors[] = 'Einige ausgewählte Tickets gehören zu Abteilungen, auf die Sie keinen Zugriff haben, und wurden übersprungen.';
|
||||
}
|
||||
|
||||
$now = db_now();
|
||||
foreach ($allowedTickets as $t) {
|
||||
if ($bulkAction === 'assign') {
|
||||
$newAgent = $_POST['bulk_assigned_staff_id'] !== '' ? (int) $_POST['bulk_assigned_staff_id'] : null;
|
||||
$pdo->prepare('UPDATE tickets SET assigned_staff_id=?, updated_at=? WHERE id=?')->execute([$newAgent, $now, $t['id']]);
|
||||
log_activity($pdo, $t['id'], $staff['id'], 'Sammelaktion: Mitarbeiter zugewiesen');
|
||||
} elseif ($bulkAction === 'priority') {
|
||||
$newPrio = (int) $_POST['bulk_priority_id'];
|
||||
$pdo->prepare('UPDATE tickets SET priority_id=?, updated_at=? WHERE id=?')->execute([$newPrio, $now, $t['id']]);
|
||||
log_activity($pdo, $t['id'], $staff['id'], 'Sammelaktion: Priorität geändert');
|
||||
} elseif ($bulkAction === 'status') {
|
||||
$newStatus = $_POST['bulk_status'];
|
||||
$resolvedAt = $newStatus === 'resolved' ? $now : $t['resolved_at'];
|
||||
$closedAt = $newStatus === 'closed' ? $now : $t['closed_at'];
|
||||
$pdo->prepare('UPDATE tickets SET status=?, resolved_at=?, closed_at=?, updated_at=? WHERE id=?')
|
||||
->execute([$newStatus, $resolvedAt, $closedAt, $now, $t['id']]);
|
||||
log_activity($pdo, $t['id'], $staff['id'], 'Sammelaktion: Status geändert');
|
||||
} elseif ($bulkAction === 'delete') {
|
||||
delete_ticket($pdo, $t, $staff['id']);
|
||||
} elseif ($bulkAction === 'ban') {
|
||||
$email = $t['requester_email'];
|
||||
$domain = $email ? substr($email, strpos($email,'@')+1) : '';
|
||||
if ($email) {
|
||||
$chk = $pdo->prepare('SELECT id FROM banlist WHERE value=?');
|
||||
$chk->execute([$email]);
|
||||
if (!$chk->fetchColumn()) {
|
||||
$pdo->prepare('INSERT INTO banlist (match_type,value,reason,created_by,created_at) VALUES (?,?,?,?,?)')
|
||||
->execute(['email', $email, 'Bulk-Sperre', $staff['id'], $now]);
|
||||
}
|
||||
// Alle Tickets dieses Absenders schließen
|
||||
$pdo->prepare("UPDATE tickets SET status='closed',closed_at=?,updated_at=? WHERE requester_email=? AND status NOT IN ('closed')")
|
||||
->execute([$now, $now, $email]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$bulkErrors) {
|
||||
$verb = ['assign' => 'zugewiesen', 'priority' => 'Priorität geändert', 'status' => 'Status geändert', 'delete' => 'gelöscht'][$bulkAction] ?? 'aktualisiert';
|
||||
flash('success', count($allowedTickets) . ' Ticket(s) ' . $verb . '.');
|
||||
} else {
|
||||
foreach ($bulkErrors as $e) flash('error', $e);
|
||||
}
|
||||
redirect('/staff/tickets.php?' . http_build_query($_GET));
|
||||
}
|
||||
}
|
||||
|
||||
$filterDept = $_GET['department_id'] ?? '';
|
||||
$filterStatus = $_GET['status'] ?? '';
|
||||
$filterPrio = $_GET['priority_id'] ?? '';
|
||||
$filterAssign = $_GET['assigned'] ?? '';
|
||||
$filterTag = $_GET['tag_id'] ?? '';
|
||||
$filterSpam = $_GET['spam'] ?? '';
|
||||
$filterSla = $_GET['sla'] ?? '';
|
||||
|
||||
$search = trim($_GET['q'] ?? '');
|
||||
$activeQuick = $_GET['quick'] ?? ''; // 'me', 'unassigned', 'overdue', 'highprio'
|
||||
|
||||
$where = [];
|
||||
$params = [];
|
||||
|
||||
// Spam-Tickets sind standardmäßig aus der normalen Ticketliste ausgeblendet.
|
||||
if ($filterSpam === '1') {
|
||||
$where[] = 't.is_spam = 1';
|
||||
} else {
|
||||
$where[] = 't.is_spam = 0';
|
||||
}
|
||||
|
||||
[$deptFilter, $deptParams] = dept_filter_sql($myDeptIds, 't.department_id');
|
||||
if ($deptFilter !== '') { $where[] = substr($deptFilter, 5); array_push($params, ...$deptParams); }
|
||||
|
||||
// Schnellfilter-Tabs
|
||||
if ($activeQuick === 'me') {
|
||||
$where[] = 't.assigned_staff_id = ?'; $params[] = $staff['id'];
|
||||
$where[] = "t.status NOT IN ('resolved','closed')";
|
||||
} elseif ($activeQuick === 'unassigned') {
|
||||
$where[] = 't.assigned_staff_id IS NULL';
|
||||
$where[] = "t.status NOT IN ('resolved','closed')";
|
||||
} elseif ($activeQuick === 'overdue') {
|
||||
$where[] = 't.resolution_due_at < ?'; $params[] = db_now();
|
||||
$where[] = "t.status NOT IN ('resolved','closed')";
|
||||
} elseif ($activeQuick === 'highprio') {
|
||||
$where[] = 't.priority_id IN (SELECT id FROM (SELECT id FROM priorities ORDER BY sort_order DESC LIMIT 2) AS top_priorities)';
|
||||
$where[] = "t.status NOT IN ('resolved','closed')";
|
||||
}
|
||||
|
||||
if ($filterDept !== '') { $where[] = 't.department_id = ?'; $params[] = $filterDept; }
|
||||
if ($filterStatus !== '' && !isset($_GET['tab'])) { $where[] = 't.status = ?'; $params[] = $filterStatus; }
|
||||
if ($filterPrio !== '') { $where[] = 't.priority_id = ?'; $params[] = $filterPrio; }
|
||||
if ($filterAssign === 'me') { $where[] = 't.assigned_staff_id = ?'; $params[] = $staff['id']; }
|
||||
elseif ($filterAssign === 'unassigned') { $where[] = 't.assigned_staff_id IS NULL'; }
|
||||
elseif ($filterAssign !== '') { $where[] = 't.assigned_staff_id = ?'; $params[] = $filterAssign; }
|
||||
if ($filterTag !== '') {
|
||||
$where[] = 't.id IN (SELECT ticket_id FROM ticket_tags WHERE tag_id = ?)';
|
||||
$params[] = $filterTag;
|
||||
}
|
||||
// SLA-Status: "at_risk" = Lösungsfrist läuft innerhalb der nächsten 4 Stunden ab, aber
|
||||
// noch nicht überschritten. "overdue"/"on_time" ergänzen sich mit is_overdue (siehe
|
||||
// cron/check_sla.php), berücksichtigen aber auch Tickets, deren Frist gerade erst
|
||||
// (zwischen zwei Cron-Läufen) verstrichen ist, statt sich blind auf das Flag zu verlassen.
|
||||
if ($filterSla !== '') {
|
||||
$now = db_now();
|
||||
$riskThreshold = date('Y-m-d H:i:s', time() + 4 * 3600);
|
||||
if ($filterSla === 'overdue') {
|
||||
$where[] = "t.resolution_due_at IS NOT NULL AND t.resolution_due_at < ? AND t.status NOT IN ('resolved','closed')";
|
||||
$params[] = $now;
|
||||
} elseif ($filterSla === 'at_risk') {
|
||||
$where[] = "t.resolution_due_at IS NOT NULL AND t.resolution_due_at >= ? AND t.resolution_due_at < ? AND t.status NOT IN ('resolved','closed')";
|
||||
array_push($params, $now, $riskThreshold);
|
||||
} elseif ($filterSla === 'on_time') {
|
||||
$where[] = "(t.resolution_due_at IS NULL OR t.resolution_due_at >= ?) AND t.status NOT IN ('resolved','closed')";
|
||||
$params[] = $riskThreshold;
|
||||
}
|
||||
}
|
||||
if ($search !== '') {
|
||||
$like = '%' . $search . '%';
|
||||
if (!empty($_GET['fulltext'])) {
|
||||
$where[] = '(t.subject LIKE ? OR t.ticket_number LIKE ? OR t.requester_email LIKE ? OR t.requester_name LIKE ?
|
||||
OR t.id IN (SELECT ticket_id FROM ticket_threads WHERE message LIKE ?))';
|
||||
array_push($params, $like, $like, $like, $like, $like);
|
||||
} else {
|
||||
$where[] = '(t.subject LIKE ? OR t.ticket_number LIKE ? OR t.requester_email LIKE ? OR t.requester_name LIKE ?)';
|
||||
array_push($params, $like, $like, $like, $like);
|
||||
}
|
||||
}
|
||||
$activeTab = $_GET['tab'] ?? 'open';
|
||||
|
||||
// Bedingung: Ticket ist von gesperrtem Absender
|
||||
$notBannedSql = "(t.requester_email NOT IN (SELECT value FROM banlist WHERE match_type='email')
|
||||
AND " . sql_email_domain("t.requester_email") . " NOT IN (SELECT value FROM banlist WHERE match_type='domain'))";
|
||||
|
||||
if ($activeTab === 'banned') {
|
||||
// Nur gesperrte Absender zeigen
|
||||
$where[] = "(t.requester_email IN (SELECT value FROM banlist WHERE match_type='email')
|
||||
OR " . sql_email_domain("t.requester_email") . " IN (SELECT value FROM banlist WHERE match_type='domain'))";
|
||||
} else {
|
||||
// Gesperrte Absender in ALLEN anderen Tabs ausblenden
|
||||
$where[] = $notBannedSql;
|
||||
|
||||
if ($activeTab === 'open') {
|
||||
$where[] = "t.status IN ('open','pending','answered')";
|
||||
} elseif ($activeTab === 'on_hold') {
|
||||
$where[] = "t.status = 'on_hold'";
|
||||
} elseif ($activeTab === 'resolved') {
|
||||
$where[] = "t.status = 'resolved'";
|
||||
} elseif ($activeTab === 'closed') {
|
||||
$where[] = "t.status = 'closed'";
|
||||
} elseif ($activeTab === 'all') {
|
||||
// kein weiterer Filter
|
||||
} else {
|
||||
$where[] = "t.status IN ('open','pending','answered')";
|
||||
}
|
||||
}
|
||||
|
||||
$sql = "SELECT t.*, p.name AS priority_name, p.color AS priority_color, d.name AS department_name, s.name AS staff_name
|
||||
FROM tickets t
|
||||
JOIN priorities p ON p.id = t.priority_id
|
||||
JOIN departments d ON d.id = t.department_id
|
||||
LEFT JOIN staff s ON s.id = t.assigned_staff_id";
|
||||
if ($where) {
|
||||
$sql .= ' WHERE ' . implode(' AND ', $where);
|
||||
}
|
||||
$page = max(1, (int)($_GET['page'] ?? 1));
|
||||
$perPage = 50;
|
||||
$offset = ($page - 1) * $perPage;
|
||||
|
||||
// Gesamtanzahl
|
||||
$countSql = "SELECT COUNT(*) FROM tickets t JOIN priorities p ON p.id = t.priority_id JOIN departments d ON d.id = t.department_id LEFT JOIN staff s ON s.id = t.assigned_staff_id"
|
||||
. ($where ? ' WHERE ' . implode(' AND ', $where) : '');
|
||||
$countStmt = $pdo->prepare($countSql);
|
||||
$countStmt->execute($params);
|
||||
$totalCount = (int)$countStmt->fetchColumn();
|
||||
$totalPages = max(1, (int)ceil($totalCount / $perPage));
|
||||
|
||||
$sql .= ' ORDER BY t.created_at DESC LIMIT ' . $perPage . ' OFFSET ' . $offset;
|
||||
|
||||
$stmt = $pdo->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$tickets = $stmt->fetchAll();
|
||||
|
||||
// Tags je angezeigtem Ticket nachladen (eine Abfrage für alle sichtbaren Tickets)
|
||||
$ticketTags = [];
|
||||
if ($tickets) {
|
||||
$ids = array_column($tickets, 'id');
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
$tagStmt = $pdo->prepare(
|
||||
"SELECT tt.ticket_id, tg.id, tg.name, tg.color FROM ticket_tags tt
|
||||
JOIN tags tg ON tg.id = tt.tag_id WHERE tt.ticket_id IN ({$placeholders})"
|
||||
);
|
||||
$tagStmt->execute($ids);
|
||||
foreach ($tagStmt->fetchAll() as $row) {
|
||||
$ticketTags[$row['ticket_id']][] = $row;
|
||||
}
|
||||
}
|
||||
$allTags = $pdo->query('SELECT * FROM tags ORDER BY name')->fetchAll();
|
||||
|
||||
// Sichtbare Abteilungen für das Filter-Dropdown auf Zugriffsrechte beschränken
|
||||
$visibleDepartments = $myDeptIds === null ? $departments : array_filter($departments, fn($d) => in_array((int) $d['id'], $myDeptIds, true));
|
||||
|
||||
// Schnellfilter-Zähler
|
||||
$_stMe = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE assigned_staff_id=? AND status NOT IN ('resolved','closed')");
|
||||
$_stMe->execute([$staff['id']]);
|
||||
$countMe = (int)$_stMe->fetchColumn();
|
||||
$countUnassigned= (int)$pdo->query("SELECT COUNT(*) FROM tickets WHERE assigned_staff_id IS NULL AND status NOT IN ('resolved','closed')")->fetchColumn();
|
||||
$_stOd = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE resolution_due_at < ? AND status NOT IN ('resolved','closed')");
|
||||
$_stOd->execute([db_now()]);
|
||||
$countOverdue = (int)$_stOd->fetchColumn();
|
||||
$countHighPrio = (int)$pdo->query("SELECT COUNT(*) FROM tickets WHERE status NOT IN ('resolved','closed') AND priority_id IN (SELECT id FROM (SELECT id FROM priorities ORDER BY sort_order DESC LIMIT 2) AS top_priorities)")->fetchColumn();
|
||||
|
||||
// Live-Refresh der Ticketliste ohne Seiten-Reload (siehe <script> weiter unten): liefert
|
||||
// bei ?partial=1 nur die Tabelle/Pagination aus derselben Query-Logik wie oben, damit
|
||||
// Filter/Seite/Sortierung 1:1 übereinstimmen und nichts doppelt gepflegt werden muss.
|
||||
if (($_GET['partial'] ?? '') === '1') {
|
||||
require __DIR__ . '/_tickets_list_partial.php';
|
||||
exit;
|
||||
}
|
||||
|
||||
$pageTitle = 'Tickets';
|
||||
$activePage = 'tickets';
|
||||
require __DIR__ . '/_header.php';
|
||||
?>
|
||||
|
||||
<?php
|
||||
// Ticket-Zähler für Tabs
|
||||
$tabCounts = [];
|
||||
foreach (['open'=>"status IN ('open','pending','answered')", 'on_hold'=>"status='on_hold'", 'resolved'=>"status='resolved'", 'closed'=>"status='closed'"] as $tk => $tcond) {
|
||||
$tabCounts[$tk] = (int)$pdo->query("SELECT COUNT(*) FROM tickets WHERE $tcond")->fetchColumn();
|
||||
}
|
||||
// Gesperrt-Tab: sicher mit try/catch
|
||||
try {
|
||||
$tabCounts['banned'] = (int)$pdo->query(
|
||||
"SELECT COUNT(*) FROM tickets WHERE requester_email IN (SELECT value FROM banlist WHERE match_type='email')
|
||||
OR " . sql_email_domain("requester_email") . " IN (SELECT value FROM banlist WHERE match_type='domain')"
|
||||
)->fetchColumn();
|
||||
} catch (Exception $e) { $tabCounts['banned'] = 0; }
|
||||
?>
|
||||
<div class="topbar">
|
||||
<h1>Tickets</h1>
|
||||
<a href="/staff/ticket_create.php" class="btn">+ Ticket erstellen</a>
|
||||
</div>
|
||||
|
||||
<!-- Tabs + Schnellfilter-Dropdown -->
|
||||
<?php
|
||||
$activeQuick = $_GET['quick'] ?? '';
|
||||
$statusTabs = [
|
||||
'open' => ['Offen', $tabCounts['open']],
|
||||
'on_hold' => ['Pausiert', $tabCounts['on_hold']],
|
||||
'resolved' => ['Gelöst', $tabCounts['resolved']],
|
||||
'closed' => ['Geschlossen', $tabCounts['closed']],
|
||||
'banned' => ['⛔ Gesperrt', $tabCounts['banned']],
|
||||
'all' => ['Alle', array_sum($tabCounts)],
|
||||
];
|
||||
$quickFilters = [
|
||||
'me' => ['Mir zugewiesen', $countMe, 'var(--primary)', '#e6f4f3'],
|
||||
'unassigned' => ['Nicht zugewiesen', $countUnassigned, '#64748b', '#f1f5f9'],
|
||||
'overdue' => ['Überfällig', $countOverdue, '#ef4444', '#fef2f2'],
|
||||
'highprio' => ['Hohe Priorität', $countHighPrio, '#f59e0b', '#fffbeb'],
|
||||
];
|
||||
$anyQuickActive = $activeQuick !== '';
|
||||
?>
|
||||
<div style="display:flex;gap:0;border-bottom:2px solid var(--border);margin-bottom:20px;flex-wrap:wrap;align-items:flex-end;position:relative">
|
||||
|
||||
<?php foreach ($statusTabs as $tk => [$tl, $tc]):
|
||||
$isActive = $activeTab === $tk && !$anyQuickActive;
|
||||
$href = '/staff/tickets.php?' . http_build_query(array_merge(array_diff_key($_GET, ['tab'=>'','page'=>'','quick'=>'']), ['tab'=>$tk]));
|
||||
?>
|
||||
<a href="<?= e($href) ?>"
|
||||
style="padding:9px 16px;font-size:.84rem;font-weight:<?=$isActive?'700':'400'?>;color:<?=$isActive?'var(--primary)':'var(--muted)'?>;text-decoration:none;border-bottom:2px solid <?=$isActive?'var(--primary)':'transparent'?>;margin-bottom:-2px;white-space:nowrap;display:flex;align-items:center;gap:6px">
|
||||
<?= $tl ?>
|
||||
<span style="background:<?=$isActive?'var(--primary)':'var(--border)'?>;color:<?=$isActive?'#fff':'var(--muted)'?>;font-size:.7rem;padding:1px 7px;border-radius:20px;font-weight:700"><?= number_format($tc) ?></span>
|
||||
</a>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<!-- Schnellfilter-Dropdown -->
|
||||
<div style="margin-left:auto;margin-bottom:-2px;position:relative" id="qf-wrap">
|
||||
<button id="qf-btn" onclick="toggleQF(event)" type="button"
|
||||
style="display:flex;align-items:center;gap:8px;padding:8px 14px;font-size:.83rem;font-weight:<?=$anyQuickActive?'700':'500'?>;color:<?=$anyQuickActive?'var(--primary)':'var(--muted)'?>;background:none;border:none;border-bottom:2px solid <?=$anyQuickActive?'var(--primary)':'transparent'?>;cursor:pointer;white-space:nowrap;margin-bottom:0">
|
||||
<?php if ($anyQuickActive): ?>
|
||||
<span style="width:7px;height:7px;border-radius:50%;background:<?= $quickFilters[$activeQuick][2] ?>;display:inline-block;flex-shrink:0"></span>
|
||||
<?= e($quickFilters[$activeQuick][0]) ?>
|
||||
<span style="background:<?= $quickFilters[$activeQuick][2] ?>;color:#fff;font-size:.68rem;padding:1px 6px;border-radius:20px;font-weight:700"><?= $quickFilters[$activeQuick][1] ?></span>
|
||||
<span style="font-size:.7rem;opacity:.6">✕</span>
|
||||
<?php else: ?>
|
||||
Schnellfilter <span style="font-size:.7rem">▾</span>
|
||||
<?php if (($countOverdue + $countMe) > 0): ?>
|
||||
<span style="background:#ef4444;color:#fff;font-size:.68rem;padding:1px 6px;border-radius:20px;font-weight:700"><?= $countOverdue + $countMe ?></span>
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
</button>
|
||||
|
||||
<div id="qf-panel" style="display:none;position:absolute;right:0;top:calc(100% + 6px);width:260px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);box-shadow:var(--shadow);z-index:200;padding:6px;overflow:hidden">
|
||||
<?php foreach ($quickFilters as $qk => [$ql, $qc, $qcolor, $qbg]):
|
||||
$qActive = $activeQuick === $qk;
|
||||
$qHref = $qActive ? '/staff/tickets.php' : '/staff/tickets.php?' . http_build_query(['quick' => $qk]);
|
||||
?>
|
||||
<a href="<?= e($qHref) ?>"
|
||||
style="display:flex;align-items:center;gap:10px;padding:10px 14px;border-radius:8px;text-decoration:none;background:<?=$qActive?$qbg:'transparent'?>;transition:background .12s;margin-bottom:2px"
|
||||
onmouseover="this.style.background='<?=$qActive?$qbg:"var(--border-soft)"?>'"
|
||||
onmouseout="this.style.background='<?=$qActive?$qbg:"transparent"?>'">
|
||||
<span style="width:8px;height:8px;border-radius:50%;background:<?=$qcolor?>;flex-shrink:0;opacity:<?=$qActive?'1':'.5'?>"></span>
|
||||
<span style="flex:1;font-size:.85rem;font-weight:<?=$qActive?'600':'500'?>;color:<?=$qActive?$qcolor:'var(--ink-soft)'?>;white-space:nowrap"><?= e($ql) ?></span>
|
||||
<span style="background:<?=$qc>0?$qcolor:'var(--border)'?>;color:<?=$qc>0?'#fff':'var(--muted)'?>;font-size:.72rem;padding:2px 9px;border-radius:20px;font-weight:700;flex-shrink:0"><?= $qc ?></span>
|
||||
</a>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function toggleQF(e) {
|
||||
e.stopPropagation();
|
||||
var p = document.getElementById('qf-panel');
|
||||
p.style.display = p.style.display === 'none' ? 'block' : 'none';
|
||||
}
|
||||
document.addEventListener('click', function() {
|
||||
var p = document.getElementById('qf-panel');
|
||||
if (p) p.style.display = 'none';
|
||||
});
|
||||
document.getElementById('qf-panel')?.addEventListener('click', function(e){ e.stopPropagation(); });
|
||||
</script>
|
||||
|
||||
<?php foreach ($bulkErrors as $err): ?>
|
||||
<div class="flash error"><?= e($err) ?></div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<?php
|
||||
$__queues = queues_for($pdo, (int) $staff['id']);
|
||||
$__currentFilters = queue_filters_from_web($_GET);
|
||||
$__currentQuery = http_build_query($_GET);
|
||||
?>
|
||||
<div class="card" style="margin-bottom:12px;padding:10px 14px">
|
||||
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
|
||||
<strong style="font-size:.8rem;color:var(--muted);text-transform:uppercase;letter-spacing:.05em">Ansichten</strong>
|
||||
<a href="/staff/tickets.php" class="btn secondary" style="padding:3px 12px;font-size:.82rem<?= !$_GET ? ';border-color:var(--primary);color:var(--primary)' : '' ?>">Standard</a>
|
||||
<?php foreach ($__queues as $__q):
|
||||
$__active = $__q['filters'] && queue_filters_to_web($__q['filters']) == array_filter($_GET, fn($v) => $v !== '' && $v !== null && $v !== []);
|
||||
?>
|
||||
<span style="display:inline-flex;align-items:center;gap:2px">
|
||||
<a href="/staff/tickets.php?<?= e(http_build_query(queue_filters_to_web($__q['filters']))) ?>" class="btn secondary" title="<?= $__q['mine'] ? 'Meine Ansicht' : 'Geteilt von ' . e($__q['owner_name'] ?? '') ?>"
|
||||
style="padding:3px 12px;font-size:.82rem<?= $__active ? ';border-color:var(--primary);color:var(--primary)' : '' ?>"><?= e($__q['name']) ?><?= $__q['is_shared'] ? ' ⇄' : '' ?></a>
|
||||
<?php if (queue_can_edit($__q, $staff)): ?>
|
||||
<form method="post" style="margin:0" onsubmit="return confirm('Ansicht löschen?')">
|
||||
<?= csrf_field() ?><input type="hidden" name="queue_action" value="delete"><input type="hidden" name="queue_id" value="<?= (int) $__q['id'] ?>">
|
||||
<button type="submit" title="Ansicht löschen" style="background:none;border:none;color:var(--muted);cursor:pointer;font-size:.9rem;padding:0 4px">✕</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</span>
|
||||
<?php endforeach; ?>
|
||||
<details style="margin-left:auto;position:relative">
|
||||
<summary class="btn secondary" style="padding:3px 12px;font-size:.82rem;cursor:pointer;list-style:none">Aktuelle Filter als Ansicht speichern</summary>
|
||||
<form method="post" class="card" style="position:absolute;right:0;top:34px;z-index:20;min-width:280px;padding:14px;box-shadow:var(--shadow-md, 0 8px 24px rgba(0,0,0,.2))">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="queue_action" value="save">
|
||||
<input type="hidden" name="return_query" value="<?= e($__currentQuery) ?>">
|
||||
<label for="queue_name" style="margin-top:0">Name der Ansicht</label>
|
||||
<input type="text" id="queue_name" name="queue_name" maxlength="80" placeholder="z. B. Meine überfälligen" required>
|
||||
<label style="display:flex;align-items:center;gap:8px;font-weight:400;margin-top:10px"><input type="checkbox" name="queue_shared" value="1" style="width:auto"> Für alle Mitarbeiter sichtbar</label>
|
||||
<p class="muted" style="font-size:.76rem;margin:8px 0 0">Gespeichert werden: <?= e($__currentFilters ? implode(', ', array_keys($__currentFilters)) : 'keine Filter (alle Tickets)') ?></p>
|
||||
<div class="btn-row"><button type="submit" class="btn">Speichern</button></div>
|
||||
</form>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="margin-bottom:16px">
|
||||
|
||||
<!-- ── Filter ── -->
|
||||
<form method="get">
|
||||
<div style="display:grid;grid-template-columns:1fr repeat(4,auto) auto;gap:10px;align-items:end;margin-bottom:10px">
|
||||
<div>
|
||||
<label style="font-size:.75rem;font-weight:600;color:var(--muted);display:block;margin-bottom:3px">Suche</label>
|
||||
<input type="search" name="q" value="<?= e($search) ?>"
|
||||
placeholder="Betreff · Ticket-Nr. · Kundenname · E-Mail"
|
||||
<?= $search ? 'autofocus' : '' ?>>
|
||||
</div>
|
||||
<div>
|
||||
<label style="font-size:.75rem;font-weight:600;color:var(--muted);display:block;margin-bottom:3px">Abteilung</label>
|
||||
<select name="department_id">
|
||||
<option value="">Alle</option>
|
||||
<?php foreach ($visibleDepartments as $d): ?>
|
||||
<option value="<?= $d['id'] ?>" <?= $filterDept == $d['id'] ? 'selected' : '' ?>><?= e($d['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label style="font-size:.75rem;font-weight:600;color:var(--muted);display:block;margin-bottom:3px">Status</label>
|
||||
<select name="status">
|
||||
<option value="">Alle außer Geschlossen</option>
|
||||
<?php foreach (['open'=>'Offen','pending'=>'Wartet auf Kunde','answered'=>'Beantwortet','on_hold'=>'Pausiert','resolved'=>'Gelöst','closed'=>'Geschlossen'] as $val=>$lbl): ?>
|
||||
<option value="<?= $val ?>" <?= $filterStatus === $val ? 'selected' : '' ?>><?= $lbl ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label style="font-size:.75rem;font-weight:600;color:var(--muted);display:block;margin-bottom:3px">E-Mail</label>
|
||||
<select name="spam">
|
||||
<option value="">Normale Tickets</option>
|
||||
<option value="1" <?= $filterSpam === '1' ? 'selected' : '' ?>>🚫 Spam</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label style="font-size:.75rem;font-weight:600;color:var(--muted);display:block;margin-bottom:3px">Priorität</label>
|
||||
<select name="priority_id">
|
||||
<option value="">Alle</option>
|
||||
<?php foreach ($priorities as $p): ?>
|
||||
<option value="<?= $p['id'] ?>" <?= $filterPrio == $p['id'] ? 'selected' : '' ?>><?= e($p['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label style="font-size:.75rem;font-weight:600;color:var(--muted);display:block;margin-bottom:3px">Zuweisung</label>
|
||||
<select name="assigned">
|
||||
<option value="">Alle</option>
|
||||
<option value="me" <?= $filterAssign==='me'?'selected':'' ?>>Mir zugewiesen</option>
|
||||
<option value="unassigned" <?= $filterAssign==='unassigned'?'selected':'' ?>>Nicht zugewiesen</option>
|
||||
<?php foreach ($agents as $a): ?>
|
||||
<option value="<?= $a['id'] ?>" <?= $filterAssign == $a['id'] ? 'selected' : '' ?>><?= e($a['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<?php if ($allTags): ?>
|
||||
<div>
|
||||
<label style="font-size:.75rem;font-weight:600;color:var(--muted);display:block;margin-bottom:3px">Tag</label>
|
||||
<select name="tag_id">
|
||||
<option value="">Alle</option>
|
||||
<?php foreach ($allTags as $tg): ?>
|
||||
<option value="<?= $tg['id'] ?>" <?= $filterTag == $tg['id'] ? 'selected' : '' ?>><?= e($tg['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<div>
|
||||
<label style="font-size:.75rem;font-weight:600;color:var(--muted);display:block;margin-bottom:3px">SLA-Status</label>
|
||||
<select name="sla">
|
||||
<option value="">Alle</option>
|
||||
<option value="overdue" <?= $filterSla==='overdue'?'selected':'' ?>>🔴 Überfällig</option>
|
||||
<option value="at_risk" <?= $filterSla==='at_risk'?'selected':'' ?>>🟡 Bald fällig (< 4 Std.)</option>
|
||||
<option value="on_time" <?= $filterSla==='on_time'?'selected':'' ?>>🟢 Im Zeitplan</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style="display:flex;gap:6px;align-items:flex-end">
|
||||
<button type="submit" class="btn">Filtern</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
|
||||
<label style="display:flex;align-items:center;gap:5px;font-size:.78rem;font-weight:400;cursor:pointer;color:var(--muted);margin:0">
|
||||
<input type="checkbox" name="fulltext" value="1" style="width:auto;margin:0" <?= !empty($_GET['fulltext']) ? 'checked' : '' ?>>
|
||||
Auch Nachrichten durchsuchen
|
||||
</label>
|
||||
<div style="flex:1"></div>
|
||||
<?php if ($staff['role'] === 'admin'): ?>
|
||||
<a href="/staff/export.php?type=tickets&<?= http_build_query($_GET) ?>" class="btn secondary" style="font-size:.8rem;padding:5px 12px">↓ CSV exportieren</a>
|
||||
<?php endif; ?>
|
||||
<?php if ($search || $filterStatus || $filterDept || $filterPrio || $filterAssign || $filterTag || $filterSpam): ?>
|
||||
<a href="/staff/tickets.php" class="btn secondary" style="font-size:.8rem;padding:5px 12px;color:var(--muted)">✕ Filter zurücksetzen</a>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
|
||||
<!-- ── Sammelaktionen ── -->
|
||||
<form method="post" id="bulk-form" style="margin-top:12px;padding-top:12px;border-top:1px solid var(--border)">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="bulk_action" id="bulk_action" value="">
|
||||
<div style="display:flex;gap:16px;flex-wrap:wrap;align-items:center">
|
||||
<span style="font-size:.75rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;color:var(--muted)">Auswahl:</span>
|
||||
|
||||
<div style="display:flex;align-items:center;gap:6px">
|
||||
<select id="bulk_assigned_staff_id" name="bulk_assigned_staff_id">
|
||||
<option value="">– nicht zugewiesen –</option>
|
||||
<?php foreach ($agents as $a): ?><option value="<?= $a['id'] ?>"><?= e($a['name']) ?></option><?php endforeach; ?>
|
||||
</select>
|
||||
<button type="button" class="btn secondary" style="white-space:nowrap" onclick="submitBulk('assign')">Zuweisen</button>
|
||||
</div>
|
||||
|
||||
<div style="display:flex;align-items:center;gap:6px">
|
||||
<select id="bulk_priority_id" name="bulk_priority_id">
|
||||
<?php foreach ($priorities as $p): ?><option value="<?= $p['id'] ?>"><?= e($p['name']) ?></option><?php endforeach; ?>
|
||||
</select>
|
||||
<button type="button" class="btn secondary" style="white-space:nowrap" onclick="submitBulk('priority')">Priorität setzen</button>
|
||||
</div>
|
||||
|
||||
<div style="display:flex;align-items:center;gap:6px">
|
||||
<select id="bulk_status" name="bulk_status">
|
||||
<?php foreach (['open'=>'Offen','pending'=>'Wartet auf Kunde','resolved'=>'Gelöst','closed'=>'Geschlossen'] as $val=>$lbl): ?>
|
||||
<option value="<?= $val ?>"><?= $lbl ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<button type="button" class="btn secondary" style="white-space:nowrap" onclick="submitBulk('status')">Status setzen</button>
|
||||
</div>
|
||||
|
||||
<div style="margin-left:auto;display:flex;gap:8px">
|
||||
<button type="button" class="btn secondary" style="border-color:#f59e0b;color:#92400e;white-space:nowrap"
|
||||
onclick="if(confirm('Alle Absender der markierten Tickets sperren und Tickets schließen?')) submitBulk('ban')">⛔ Absender sperren</button>
|
||||
<button type="button" class="btn danger" style="white-space:nowrap"
|
||||
onclick="if(confirm('Markierte Tickets wirklich unwiderruflich löschen?')) submitBulk('delete')">Löschen</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
</div>
|
||||
|
||||
<?php require __DIR__ . '/_tickets_list_partial.php'; ?>
|
||||
|
||||
<script>
|
||||
function submitBulk(action) {
|
||||
const checked = document.querySelectorAll('.ticket-check:checked');
|
||||
if (checked.length === 0) { alert('Bitte mindestens ein Ticket markieren.'); return; }
|
||||
|
||||
// Copy checked ticket IDs into the top bulk-form and submit
|
||||
const form = document.getElementById('bulk-form');
|
||||
document.getElementById('bulk_action').value = action;
|
||||
|
||||
// Remove any previously cloned ticket_id inputs
|
||||
form.querySelectorAll('input[name="ticket_ids[]"]').forEach(el => el.remove());
|
||||
|
||||
// Clone the checked ticket IDs into the bulk-form
|
||||
checked.forEach(cb => {
|
||||
const inp = document.createElement('input');
|
||||
inp.type = 'hidden';
|
||||
inp.name = 'ticket_ids[]';
|
||||
inp.value = cb.value;
|
||||
form.appendChild(inp);
|
||||
});
|
||||
|
||||
form.submit();
|
||||
}
|
||||
|
||||
// Live-Refresh: holt alle paar Sekunden die aktuelle Ticketliste (gleiche Filter/Seite
|
||||
// über die URL) im Hintergrund und tauscht nur die Tabelle aus – so tauchen neue oder
|
||||
// geänderte Tickets automatisch auf, ohne dass ein Mitarbeiter die Seite neu laden muss.
|
||||
// Pausiert bewusst, solange gerade Tickets markiert sind (Sammelaktion in Vorbereitung)
|
||||
// oder der Nutzer gerade in einem Formularfeld tippt/eine Auswahl offen hat, damit nichts
|
||||
// unter den Fingern weggezogen wird.
|
||||
(function () {
|
||||
var region = document.getElementById('tickets-live-region');
|
||||
if (!region) return;
|
||||
var refreshing = false;
|
||||
|
||||
function partialUrl() {
|
||||
var params = new URLSearchParams(window.location.search);
|
||||
params.set('partial', '1');
|
||||
return window.location.pathname + '?' + params.toString();
|
||||
}
|
||||
|
||||
function refreshTicketList() {
|
||||
if (refreshing) return;
|
||||
if (document.querySelectorAll('.ticket-check:checked').length > 0) return;
|
||||
var active = document.activeElement;
|
||||
if (active && ['INPUT', 'SELECT', 'TEXTAREA'].includes(active.tagName)) return;
|
||||
|
||||
refreshing = true;
|
||||
fetch(partialUrl(), { credentials: 'same-origin' })
|
||||
.then(function (r) { return r.text(); })
|
||||
.then(function (html) {
|
||||
var tmp = document.createElement('div');
|
||||
tmp.innerHTML = html;
|
||||
var fresh = tmp.querySelector('#tickets-live-region');
|
||||
if (fresh) {
|
||||
region.replaceWith(fresh);
|
||||
region = fresh;
|
||||
}
|
||||
})
|
||||
.catch(function () {})
|
||||
.finally(function () { refreshing = false; });
|
||||
}
|
||||
|
||||
setInterval(refreshTicketList, 15000);
|
||||
})();
|
||||
</script>
|
||||
|
||||
<?php require __DIR__ . '/_footer.php'; ?>
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_admin_or_permission('view_time_entries');
|
||||
$pdo = get_db();
|
||||
|
||||
$filterStaff = $_GET['staff_id'] ?? '';
|
||||
$filterFrom = $_GET['from'] ?? date('Y-m-01');
|
||||
$filterTo = $_GET['to'] ?? date('Y-m-d');
|
||||
|
||||
$allStaff = $pdo->query('SELECT id, name FROM staff WHERE is_active=1 ORDER BY name')->fetchAll();
|
||||
|
||||
$where = ['te.logged_at BETWEEN ? AND ?'];
|
||||
$params = [$filterFrom . ' 00:00:00', $filterTo . ' 23:59:59'];
|
||||
|
||||
if ($filterStaff !== '') {
|
||||
$where[] = 'te.staff_id = ?';
|
||||
$params[] = $filterStaff;
|
||||
}
|
||||
|
||||
$stmt = $pdo->prepare(
|
||||
"SELECT te.*, s.name AS staff_name, t.ticket_number, t.subject
|
||||
FROM ticket_time_entries te
|
||||
JOIN staff s ON s.id = te.staff_id
|
||||
JOIN tickets t ON t.id = te.ticket_id
|
||||
WHERE " . implode(' AND ', $where) . "
|
||||
ORDER BY te.logged_at DESC
|
||||
LIMIT 500"
|
||||
);
|
||||
$stmt->execute($params);
|
||||
$entries = $stmt->fetchAll();
|
||||
|
||||
// Summen je Mitarbeiter
|
||||
$byStaff = [];
|
||||
foreach ($entries as $e) {
|
||||
$byStaff[$e['staff_name']] = ($byStaff[$e['staff_name']] ?? 0) + (int)$e['minutes'];
|
||||
}
|
||||
|
||||
$totalMinutes = array_sum(array_column($entries, 'minutes'));
|
||||
|
||||
$pageTitle = 'Zeiterfassung';
|
||||
$activePage = 'time_entries';
|
||||
require __DIR__ . '/_header.php';
|
||||
|
||||
function fmt_minutes(int $m): string {
|
||||
return floor($m / 60) . 'h ' . ($m % 60) . 'min';
|
||||
}
|
||||
?>
|
||||
|
||||
<div class="topbar">
|
||||
<h1>⏱ Zeiterfassung</h1>
|
||||
</div>
|
||||
|
||||
<form method="get" class="filters card" style="margin-bottom:16px">
|
||||
<div>
|
||||
<label>Von</label>
|
||||
<input type="date" name="from" value="<?= e($filterFrom) ?>">
|
||||
</div>
|
||||
<div>
|
||||
<label>Bis</label>
|
||||
<input type="date" name="to" value="<?= e($filterTo) ?>">
|
||||
</div>
|
||||
<div>
|
||||
<label>Mitarbeiter</label>
|
||||
<select name="staff_id">
|
||||
<option value="">Alle</option>
|
||||
<?php foreach ($allStaff as $s): ?>
|
||||
<option value="<?= $s['id'] ?>" <?= $filterStaff == $s['id'] ? 'selected' : '' ?>><?= e($s['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div><button type="submit" class="btn secondary">Filtern</button></div>
|
||||
</form>
|
||||
|
||||
<?php if ($byStaff): ?>
|
||||
<div class="stat-grid" style="margin-bottom:20px">
|
||||
<?php foreach ($byStaff as $name => $mins): ?>
|
||||
<div class="stat-card">
|
||||
<div class="num" style="font-size:1.4rem"><?= fmt_minutes($mins) ?></div>
|
||||
<div class="lbl"><?= e($name) ?></div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
<div class="stat-card" style="border-color:var(--primary)">
|
||||
<div class="num" style="font-size:1.4rem; color:var(--primary)"><?= fmt_minutes($totalMinutes) ?></div>
|
||||
<div class="lbl">Gesamt</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="card">
|
||||
<?php if (!$entries): ?>
|
||||
<div class="empty-state">Keine Zeiteinträge im gewählten Zeitraum.</div>
|
||||
<?php else: ?>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Datum</th>
|
||||
<th>Mitarbeiter</th>
|
||||
<th>Ticket</th>
|
||||
<th>Betreff</th>
|
||||
<th>Zeit</th>
|
||||
<th>Notiz</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($entries as $e): ?>
|
||||
<tr>
|
||||
<td class="muted"><?= format_dt($e['logged_at']) ?></td>
|
||||
<td><?= e($e['staff_name']) ?></td>
|
||||
<td><a href="/staff/ticket_view.php?n=<?= urlencode($e['ticket_number']) ?>" class="ticket-no">#<?= e($e['ticket_number']) ?></a></td>
|
||||
<td><?= e($e['subject']) ?></td>
|
||||
<td style="white-space:nowrap; font-weight:600"><?= fmt_minutes((int)$e['minutes']) ?></td>
|
||||
<td class="muted"><?= e($e['note'] ?? '') ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<?php require __DIR__ . '/_footer.php'; ?>
|
||||
@@ -0,0 +1,420 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
require_once __DIR__ . '/../includes/backup.php';
|
||||
$staff = require_admin();
|
||||
$pdo = get_db();
|
||||
|
||||
$errors = [];
|
||||
|
||||
const UPDATE_REPO_API = 'https://git.viper.ipv64.net/api/v1/repos/M_Viper/deskhub';
|
||||
|
||||
/** Lädt eine https-Adresse (Weiterleitungen nur auf https). Gibt [Status, Inhalt, Fehlertext] zurück. */
|
||||
function update_download(string $url, array $headers, int $timeout): array
|
||||
{
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 3, CURLOPT_TIMEOUT => $timeout,
|
||||
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS, CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTPS,
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
]);
|
||||
$data = curl_exec($ch);
|
||||
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$err = curl_error($ch);
|
||||
curl_close($ch);
|
||||
return [$code, is_string($data) ? $data : '', $err];
|
||||
}
|
||||
|
||||
// ── ZIP installieren ─────────────────────────────────────────────────────────
|
||||
function do_install(string $zipPath): array
|
||||
{
|
||||
$zip = new ZipArchive();
|
||||
$openResult = $zip->open($zipPath);
|
||||
if ($openResult !== true) {
|
||||
return ['ok' => false, 'error' => 'ZIP konnte nicht geöffnet werden (Code: ' . $openResult . ', Datei: ' . $zipPath . ', Größe: ' . filesize($zipPath) . ')'];
|
||||
}
|
||||
|
||||
$rootDir = str_replace('/', DIRECTORY_SEPARATOR, realpath(__DIR__ . '/..'));
|
||||
$protected = [
|
||||
'config/config.php',
|
||||
'database/deskhub.sqlite',
|
||||
'database/deskhub.db',
|
||||
'.env',
|
||||
'version.php',
|
||||
'staff/update.php', // Sich selbst nicht überschreiben während des Updates
|
||||
'includes/bootstrap.php', // Bootstrap nicht mid-request überschreiben
|
||||
];
|
||||
|
||||
// Gitea-Prefix erkennen (z.B. "deskhub/")
|
||||
$prefix = '';
|
||||
for ($i = 0; $i < min($zip->numFiles, 5); $i++) {
|
||||
$n = $zip->getNameIndex($i);
|
||||
if (substr($n, -1) === '/' && substr_count(rtrim($n, '/'), '/') === 0) {
|
||||
$prefix = $n;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$extracted = 0;
|
||||
$failed = [];
|
||||
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$name = $zip->getNameIndex($i);
|
||||
|
||||
// Verzeichnisse überspringen
|
||||
if (substr($name, -1) === '/') continue;
|
||||
|
||||
// Prefix entfernen
|
||||
if ($prefix) {
|
||||
if (strpos($name, $prefix) !== 0) continue;
|
||||
$rel = substr($name, strlen($prefix));
|
||||
} else {
|
||||
$rel = $name;
|
||||
}
|
||||
|
||||
if ($rel === '') continue;
|
||||
|
||||
// Pfad prüfen: kein Verlassen des Installationsordners (Zip-Slip), keine absoluten Pfade
|
||||
$relNorm = str_replace(chr(92), '/', $rel);
|
||||
if ($relNorm[0] === '/' || preg_match('#(^|/)\.\.(/|$)#', $relNorm) || preg_match('#^[A-Za-z]:#', $relNorm) || strpos($relNorm, "\0") !== false) {
|
||||
$failed[] = $rel;
|
||||
continue;
|
||||
}
|
||||
// Die Plugin-Webseite und Entwickler-Werkzeuge gehören nicht auf Kunden-Installationen; Plugins, App-Dateien, Uploads und Backups gehören dem System und werden von Updates nie angefasst
|
||||
if (preg_match('#^(plugins|uploads|backups|app_downloads)/#', $relNorm) || preg_match('#^(plugin-webseite|tools|tests|docs|desktop|mobile|theme-packages|vorschaubilder|\.gitea|\.github)/#', $relNorm)) continue;
|
||||
|
||||
// Geschützte Dateien überspringen
|
||||
$skip = false;
|
||||
foreach ($protected as $p) {
|
||||
if ($rel === $p || str_replace('/', DIRECTORY_SEPARATOR, $rel) === str_replace('/', DIRECTORY_SEPARATOR, $p)) {
|
||||
$skip = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($skip) continue;
|
||||
|
||||
// Windows-Pfad
|
||||
$dest = $rootDir . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $rel);
|
||||
$dir = dirname($dest);
|
||||
|
||||
if (!is_dir($dir)) {
|
||||
mkdir($dir, 0755, true);
|
||||
}
|
||||
|
||||
$data = $zip->getFromIndex($i);
|
||||
if ($data === false) continue;
|
||||
|
||||
$written = file_put_contents($dest, $data);
|
||||
if ($written !== false) {
|
||||
$extracted++;
|
||||
} else {
|
||||
$failed[] = $rel;
|
||||
}
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
|
||||
if ($extracted === 0) {
|
||||
$msg = 'Keine Dateien extrahiert!';
|
||||
if ($prefix) $msg .= ' Prefix: "' . $prefix . '"';
|
||||
if ($failed) $msg .= ' Fehlgeschlagen: ' . implode(', ', array_slice($failed, 0, 3));
|
||||
return ['ok' => false, 'error' => $msg];
|
||||
}
|
||||
|
||||
return ['ok' => true, 'extracted' => $extracted, 'failed' => $failed];
|
||||
}
|
||||
|
||||
// ── POST ─────────────────────────────────────────────────────────────────────
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
// CSRF prüfen ohne Token-Rotation (wegen Datei-Upload multipart)
|
||||
$csrfToken = $_POST['csrf_token'] ?? '';
|
||||
if (!$csrfToken || !hash_equals($_SESSION['csrf_token'] ?? '', $csrfToken)) {
|
||||
http_response_code(403);
|
||||
die('Ungültige Anfrage (CSRF-Token fehlt oder ist ungültig). Bitte gehen Sie zurück und versuchen Sie es erneut.');
|
||||
}
|
||||
$action = $_POST['action'] ?? '';
|
||||
|
||||
// Manueller Upload
|
||||
if ($action === 'upload_update') {
|
||||
$f = $_FILES['update_zip'] ?? [];
|
||||
if (($f['error'] ?? 99) !== UPLOAD_ERR_OK) {
|
||||
$errors[] = 'Upload-Fehler Code: ' . ($f['error'] ?? 'unbekannt');
|
||||
} elseif (strtolower(pathinfo($f['name'] ?? '', PATHINFO_EXTENSION)) !== 'zip') {
|
||||
$errors[] = 'Nur ZIP-Dateien erlaubt.';
|
||||
} else {
|
||||
$tmp = $f['tmp_name'];
|
||||
$bk = create_backup();
|
||||
$res = do_install($tmp);
|
||||
if (!$res['ok']) {
|
||||
$errors[] = $res['error'];
|
||||
} else {
|
||||
// Schema-Migrationen nach Update einspielen
|
||||
require_once __DIR__ . '/../database/migrate.php';
|
||||
$mig = run_migrations(get_db());
|
||||
$migNote = $mig['applied'] > 0 ? " · {$mig['applied']} Migration(en) eingespielt" : '';
|
||||
if ($mig['errors']) $errors = array_merge($errors, $mig['errors']);
|
||||
audit_log($staff['id'], "Update installiert: {$res['extracted']} Dateien{$migNote}");
|
||||
flash('success', "✅ {$res['extracted']} Dateien aktualisiert.{$migNote}" . ($bk['ok'] ? " Backup: {$bk['filename']}" : ''));
|
||||
redirect('/staff/update.php');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Nur die Datenbank auf den Stand des installierten Codes bringen (z. B. nach Datei-Upload per FTP)
|
||||
if ($action === 'migrate_db') {
|
||||
require_once __DIR__ . '/../database/migrate.php';
|
||||
$pending = migrations_pending($pdo);
|
||||
if (!$pending) {
|
||||
flash('success', 'Die Datenbank ist bereits auf dem aktuellen Stand.');
|
||||
redirect('/staff/update.php');
|
||||
}
|
||||
$bk = create_backup();
|
||||
if (!$bk['ok']) {
|
||||
$errors[] = 'Backup fehlgeschlagen – die Datenbank wurde nicht verändert: ' . ($bk['error'] ?? 'unbekannter Fehler');
|
||||
} else {
|
||||
$mig = run_migrations($pdo);
|
||||
if ($mig['errors']) {
|
||||
$errors = array_merge($errors, $mig['errors']);
|
||||
audit_log($staff['id'], 'Datenbank-Update mit Fehlern: ' . implode('; ', $mig['errors']));
|
||||
} else {
|
||||
audit_log($staff['id'], "Datenbank aktualisiert: {$mig['applied']} Migration(en)");
|
||||
flash('success', "✅ Datenbank aktualisiert ({$mig['applied']} Migration(en)). Backup: {$bk['filename']}");
|
||||
redirect('/staff/update.php');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-Download vom Update-Server. Ist ein Herausgeber-Schlüssel eingebaut, wird nur ein signiertes Release installiert.
|
||||
if ($action === 'auto_update') {
|
||||
$tagName = trim($_POST['tag_name'] ?? '');
|
||||
$headers = update_http_headers();
|
||||
if (!preg_match('/^v?\d+\.\d+\.\d+([\-+][0-9A-Za-z.\-]+)?$/', $tagName)) {
|
||||
$errors[] = 'Kein gültiges Release gewählt.';
|
||||
} else {
|
||||
$verifyRequired = update_signature_required();
|
||||
$zipUrl = UPDATE_REPO_API === '' ? '' : 'https://git.viper.ipv64.net/M_Viper/deskhub/archive/' . rawurlencode($tagName) . '.zip';
|
||||
$sigUrl = null;
|
||||
[$relCode, $relBody] = update_download(UPDATE_REPO_API . '/releases/tags/' . rawurlencode($tagName), $headers, 10);
|
||||
$release = $relCode === 200 ? (json_decode($relBody, true) ?: []) : [];
|
||||
$assets = update_find_assets($release, $tagName);
|
||||
if ($assets['zip']) { $zipUrl = $assets['zip']; $sigUrl = $assets['sig']; }
|
||||
|
||||
if ($verifyRequired && (!$assets['zip'] || !$sigUrl)) {
|
||||
$errors[] = 'Dieses Release ist nicht signiert (Anhänge deskhub-' . ltrim($tagName, 'vV') . '.zip und .zip.sig fehlen). Aus Sicherheitsgründen wird es nicht installiert.';
|
||||
} else {
|
||||
[$code, $data, $err] = update_download($zipUrl, $headers, 120);
|
||||
if ($err) {
|
||||
$errors[] = 'cURL-Fehler: ' . $err . (stripos($err, 'certificate') !== false || stripos($err, 'SSL') !== false ? ' – Das Serverzertifikat konnte nicht geprüft werden. Bitte das CA-Zertifikatspaket des Servers aktualisieren (php.ini: curl.cainfo). Die Prüfung wird aus Sicherheitsgründen nicht abgeschaltet.' : '');
|
||||
} elseif ($code !== 200) {
|
||||
$errors[] = "Download fehlgeschlagen (HTTP $code).";
|
||||
} else {
|
||||
$tmp = tempnam(sys_get_temp_dir(), 'dh_') . '.zip';
|
||||
file_put_contents($tmp, $data);
|
||||
$sigError = null;
|
||||
if ($verifyRequired) {
|
||||
[$sc, $sigBody] = update_download($sigUrl, $headers, 20);
|
||||
$sigError = $sc === 200 ? update_verify_package($tagName, $tmp, $sigBody) : "Die Signatur konnte nicht geladen werden (HTTP $sc).";
|
||||
}
|
||||
if ($sigError !== null) {
|
||||
@unlink($tmp);
|
||||
audit_log($staff['id'], "Update $tagName abgelehnt: $sigError");
|
||||
$errors[] = $sigError;
|
||||
} else {
|
||||
$bk = create_backup();
|
||||
$res = do_install($tmp);
|
||||
@unlink($tmp);
|
||||
if (!$res['ok']) {
|
||||
$errors[] = $res['error'];
|
||||
} else {
|
||||
// Schema-Migrationen nach Update einspielen
|
||||
require_once __DIR__ . '/../database/migrate.php';
|
||||
$mig = run_migrations(get_db());
|
||||
$migNote = $mig['applied'] > 0 ? " · {$mig['applied']} Migration(en) eingespielt" : '';
|
||||
if ($mig['errors']) $errors = array_merge($errors, $mig['errors']);
|
||||
audit_log($staff['id'], "Auto-Update $tagName: {$res['extracted']} Dateien{$migNote}" . ($verifyRequired ? ' (Signatur geprüft)' : ''));
|
||||
// Versionsnummer in version.php aktualisieren
|
||||
$newVer = ltrim($tagName, 'v');
|
||||
$verFile = realpath(__DIR__ . '/../version.php');
|
||||
if ($verFile && $newVer) {
|
||||
$vc = file_get_contents($verFile);
|
||||
$vc = preg_replace("/define\('DESKHUB_VERSION',\s*'[^']+'\)/", "define('DESKHUB_VERSION', '$newVer')", $vc);
|
||||
file_put_contents($verFile, $vc);
|
||||
}
|
||||
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
|
||||
flash('success', "✅ Update auf $newVer: {$res['extracted']} Dateien." . ($verifyRequired ? ' Signatur geprüft.' : '') . ($bk['ok'] ? " Backup: {$bk['filename']}" : ''));
|
||||
redirect('/staff/update.php');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Releases laden ────────────────────────────────────────────────────────────
|
||||
$releases = [];
|
||||
$relErr = '';
|
||||
[$code, $resp] = update_download(UPDATE_REPO_API . '/releases?limit=20', update_http_headers(), 8);
|
||||
if ($code === 200) {
|
||||
$all = json_decode($resp, true) ?: [];
|
||||
usort($all, fn($a, $b) => version_compare($b['tag_name'], $a['tag_name']));
|
||||
$releases = $all;
|
||||
} else {
|
||||
$relErr = "API HTTP $code" . (update_http_headers() === [] ? ' (Ist das Repository privat? Dann in config/config.php unter update → token ein Lese-Token eintragen.)' : '');
|
||||
}
|
||||
$signedOnly = update_signature_required();
|
||||
// Version frisch aus Datei lesen
|
||||
$verFile = realpath(__DIR__ . '/../version.php') ?: '';
|
||||
$verData = $verFile ? file_get_contents($verFile) : '';
|
||||
preg_match("/define\s*\(\s*'DESKHUB_VERSION'\s*,\s*'([^']+)'/", $verData, $vm);
|
||||
$curVer = $vm[1] ?? DESKHUB_VERSION;
|
||||
$latest = $releases[0] ?? null;
|
||||
$hasUpdate = $latest && version_compare($latest['tag_name'], $curVer, '>');
|
||||
|
||||
require_once __DIR__ . '/../database/migrate.php';
|
||||
$pendingMigrations = migrations_pending($pdo);
|
||||
|
||||
$pageTitle = 'System-Update';
|
||||
$activePage = 'update';
|
||||
require __DIR__ . '/_header.php';
|
||||
?>
|
||||
|
||||
<div class="topbar"><h1>🔄 System-Update</h1></div>
|
||||
|
||||
<?php foreach ($errors as $e): ?>
|
||||
<div class="flash error"><?= htmlspecialchars($e) ?></div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<?php if ($hasUpdate): ?>
|
||||
<div style="background:#e0f2f1;border:1px solid #0f6f6a;border-radius:10px;padding:16px 20px;margin-bottom:20px;display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap">
|
||||
<div>
|
||||
<strong style="color:#0f6f6a">Update verfügbar: Version <?= htmlspecialchars($latest['tag_name']) ?></strong>
|
||||
<span style="color:#64748b;font-size:.85rem;margin-left:10px">vom <?= date('d.m.Y', strtotime($latest['published_at'])) ?></span>
|
||||
</div>
|
||||
<form method="post">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="auto_update">
|
||||
<input type="hidden" name="tag_name" value="<?= htmlspecialchars($latest['tag_name']) ?>">
|
||||
<button type="submit" class="btn" onclick="return confirm('Update auf <?= htmlspecialchars($latest['tag_name']) ?> installieren?')">Jetzt installieren</button>
|
||||
</form>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="card" style="margin-bottom:20px;<?= $pendingMigrations ? 'border-color:#d97706' : '' ?>">
|
||||
<div style="display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap">
|
||||
<div>
|
||||
<div style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);margin-bottom:6px">Datenbank</div>
|
||||
<?php if ($pendingMigrations): ?>
|
||||
<strong style="color:#b45309"><?= count($pendingMigrations) ?> ausstehende Datenbank-Änderung(en)</strong>
|
||||
<div style="color:var(--muted);font-size:.82rem;margin-top:4px">Der Code ist neuer als die Datenbank. Vor dem Einspielen wird automatisch ein Backup erstellt.</div>
|
||||
<details style="margin-top:6px;font-size:.8rem;color:var(--muted)"><summary>Details</summary><?= htmlspecialchars(implode(', ', $pendingMigrations)) ?></details>
|
||||
<?php else: ?>
|
||||
<strong style="color:#15803d">✓ Die Datenbank ist aktuell</strong>
|
||||
<div style="color:var(--muted);font-size:.82rem;margin-top:4px">Alle bekannten Datenbank-Änderungen sind eingespielt.</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<form method="post">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="migrate_db">
|
||||
<button type="submit" class="btn <?= $pendingMigrations ? '' : 'secondary' ?>" <?= $pendingMigrations ? "onclick=\"return confirm('Datenbank jetzt aktualisieren? Es wird zuerst ein Backup erstellt.')\"" : 'disabled' ?>>🗄 Datenbank aktualisieren</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">
|
||||
|
||||
<div class="card" style="margin:0">
|
||||
<div style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);margin-bottom:12px">Installierte Version</div>
|
||||
<div style="font-size:3rem;font-weight:800;color:var(--primary);line-height:1"><?= htmlspecialchars($curVer) ?></div>
|
||||
<div style="color:var(--muted);font-size:.82rem;margin-top:6px">DeskHub Ticketsystem</div>
|
||||
<?php if ($releases): ?>
|
||||
<button onclick="document.getElementById('rel-modal').style.display='flex'" class="btn secondary" style="margin-top:16px">📋 Alle Releases</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div class="card" style="margin:0">
|
||||
<div style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);margin-bottom:12px">Manuelles Update</div>
|
||||
<p style="color:var(--muted);font-size:.85rem;margin-bottom:14px">ZIP-Datei von Gitea hochladen und installieren.</p>
|
||||
<form method="post" enctype="multipart/form-data">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="upload_update">
|
||||
<input type="file" name="update_zip" accept=".zip" required style="margin-bottom:12px">
|
||||
<button type="submit" class="btn secondary">⬆️ Hochladen & installieren</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<?php if (count($releases) > 1): ?>
|
||||
<div class="card" style="margin-bottom:20px">
|
||||
<h3>Bestimmte Version installieren</h3>
|
||||
<form method="post" style="display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="auto_update">
|
||||
<div style="flex:1;min-width:200px">
|
||||
<select name="tag_name" required>
|
||||
<option value="">– Version wählen –</option>
|
||||
<?php foreach ($releases as $r): $isCur = $r['tag_name']===$curVer; ?>
|
||||
<option value="<?= htmlspecialchars($r['tag_name']) ?>" <?= $isCur?'disabled':'' ?>>
|
||||
<?= htmlspecialchars($r['tag_name']) ?><?= $isCur?' (installiert)':'' ?> – <?= date('d.m.Y', strtotime($r['published_at'])) ?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<button type="submit" class="btn secondary" onclick="return confirm('Version installieren?')">Installieren</button>
|
||||
</form>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="card">
|
||||
<h3>Hinweise</h3>
|
||||
<ul style="padding-left:20px;line-height:2;font-size:.88rem;color:var(--muted)">
|
||||
<li><strong style="color:var(--ink)">config/config.php</strong> und <strong style="color:var(--ink)">database/deskhub.sqlite</strong> werden niemals überschrieben</li>
|
||||
<?php if ($signedOnly): ?><li><strong style="color:var(--ink)">Nur signierte Releases:</strong> Updates werden nur installiert, wenn sie mit dem Schlüssel des Herausgebers signiert sind. Ein manipuliertes Paket wird abgelehnt. (Ein manuell hochgeladenes ZIP wird nicht geprüft: Laden Sie nur Pakete aus vertrauenswürdiger Quelle hoch.)</li><?php endif; ?>
|
||||
<?php if ($relErr): ?><li style="color:#b45309">Release-Liste konnte nicht geladen werden: <?= htmlspecialchars($relErr) ?></li><?php endif; ?>
|
||||
<li>Nach dem Update Browser-Cache leeren <kbd>Strg+F5</kbd></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!-- Releases Modal -->
|
||||
<div id="rel-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;align-items:center;justify-content:center;padding:20px">
|
||||
<div style="background:#fff;border-radius:14px;width:100%;max-width:600px;max-height:80vh;display:flex;flex-direction:column">
|
||||
<div style="display:flex;align-items:center;justify-content:space-between;padding:18px 24px;border-bottom:1px solid var(--border)">
|
||||
<h3 style="margin:0">Releases</h3>
|
||||
<button onclick="document.getElementById('rel-modal').style.display='none'" style="background:none;border:none;font-size:1.5rem;cursor:pointer;color:var(--muted)">×</button>
|
||||
</div>
|
||||
<div style="overflow-y:auto;padding:20px 24px">
|
||||
<?php foreach ($releases as $r):
|
||||
$isNew = version_compare($r['tag_name'], $curVer, '>');
|
||||
$isCur = $r['tag_name'] === $curVer;
|
||||
?>
|
||||
<div style="border:1px solid var(--border);border-radius:8px;padding:14px 16px;margin-bottom:10px<?= $isNew?';border-color:var(--primary)':'' ?>">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
|
||||
<div style="display:flex;gap:8px;align-items:center">
|
||||
<strong><?= htmlspecialchars($r['tag_name']) ?></strong>
|
||||
<?php if ($isNew): ?><span style="background:var(--primary);color:#fff;font-size:.7rem;padding:2px 8px;border-radius:20px;font-weight:700">NEU</span><?php endif; ?>
|
||||
<?php if ($isCur): ?><span style="background:#e2f5f3;color:var(--primary);font-size:.7rem;padding:2px 8px;border-radius:20px;font-weight:700">INSTALLIERT</span><?php endif; ?>
|
||||
</div>
|
||||
<span style="color:var(--muted);font-size:.78rem"><?= date('d.m.Y', strtotime($r['published_at'])) ?></span>
|
||||
</div>
|
||||
<?php if (!empty($r['body'])): ?>
|
||||
<div style="font-size:.83rem;color:var(--muted);white-space:pre-wrap;margin-bottom:10px"><?= htmlspecialchars(mb_substr($r['body'], 0, 200)) ?><?= mb_strlen($r['body'])>200?'…':'' ?></div>
|
||||
<?php endif; ?>
|
||||
<?php if (!$isCur): ?>
|
||||
<form method="post" onsubmit="return confirm('<?= htmlspecialchars($r['tag_name']) ?> installieren?')">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="auto_update">
|
||||
<input type="hidden" name="tag_name" value="<?= htmlspecialchars($r['tag_name']) ?>">
|
||||
<button type="submit" class="btn <?= $isNew?'':'secondary' ?>" style="font-size:.82rem;padding:6px 14px">⬆️ Installieren</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
document.getElementById('rel-modal')?.addEventListener('click', function(e){ if(e.target===this) this.style.display='none'; });
|
||||
document.addEventListener('keydown', function(e){ if(e.key==='Escape') document.getElementById('rel-modal').style.display='none'; });
|
||||
</script>
|
||||
|
||||
<?php require __DIR__ . '/_footer.php'; ?>
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
$staff = require_admin();
|
||||
|
||||
$zipName = $_SESSION['update_zip'] ?? '';
|
||||
if (!$zipName || !preg_match('/^deskhub-update-[\w\.\-]+\.zip$/', $zipName)) {
|
||||
http_response_code(400); die('Kein Update-ZIP vorhanden.');
|
||||
}
|
||||
|
||||
$zipPath = realpath(__DIR__ . '/../downloads') . '/' . $zipName;
|
||||
if (!file_exists($zipPath)) {
|
||||
http_response_code(404); die('Datei nicht gefunden.');
|
||||
}
|
||||
|
||||
header('Content-Type: application/zip');
|
||||
header('Content-Disposition: attachment; filename="' . $zipName . '"');
|
||||
header('Content-Length: ' . filesize($zipPath));
|
||||
header('Cache-Control: private, no-cache');
|
||||
readfile($zipPath);
|
||||
|
||||
// Nach Download aufräumen
|
||||
unlink($zipPath);
|
||||
unset($_SESSION['update_zip'], $_SESSION['update_version'], $_SESSION['update_backup']);
|
||||
exit;
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
require_staff_login();
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
http_response_code(405);
|
||||
echo json_encode(['error' => 'Nur POST erlaubt.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
verify_csrf();
|
||||
|
||||
if (empty($_FILES['image'])) {
|
||||
http_response_code(422);
|
||||
echo json_encode(['error' => 'Bitte eine Bilddatei auswählen.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$file = $_FILES['image'];
|
||||
$allowedImageExts = array_values(array_intersect(get_allowed_extensions(), ['png', 'jpg', 'jpeg', 'gif']));
|
||||
$ext = strtolower(pathinfo($file['name'] ?? '', PATHINFO_EXTENSION));
|
||||
|
||||
if ($file['error'] !== UPLOAD_ERR_OK) {
|
||||
http_response_code(422);
|
||||
echo json_encode(['error' => 'Der Upload ist fehlgeschlagen.']);
|
||||
exit;
|
||||
}
|
||||
if (!in_array($ext, $allowedImageExts, true)) {
|
||||
http_response_code(422);
|
||||
echo json_encode(['error' => 'Nur Bilder erlaubt (' . implode(', ', array_map('strtoupper', $allowedImageExts)) . ').']);
|
||||
exit;
|
||||
}
|
||||
if ($file['size'] > 5 * 1024 * 1024) {
|
||||
http_response_code(422);
|
||||
echo json_encode(['error' => 'Die Datei ist zu groß (max. 5 MB).']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$result = handle_ticket_upload($file);
|
||||
if (isset($result['error'])) {
|
||||
http_response_code(422);
|
||||
echo json_encode(['error' => $result['error']]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$staff = current_staff();
|
||||
audit_log($staff['id'], "Bild hochgeladen: {$result['stored_name']}");
|
||||
|
||||
// verify_csrf() hat den Session-Token bereits rotiert – der neue Wert muss zurück an die Seite,
|
||||
// sonst schlägt das nachfolgende Absenden des umgebenden Formulars (z.B. Signatur speichern) fehl.
|
||||
echo json_encode([
|
||||
'url' => base_url() . '/uploads/' . $result['stored_name'],
|
||||
'csrfToken' => csrf_token(),
|
||||
]);
|
||||
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||||
require_once __DIR__ . '/_ui.php';
|
||||
$staff = require_admin();
|
||||
$pdo = get_db();
|
||||
|
||||
$errors = [];
|
||||
$eventLabels = webhook_event_labels();
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
verify_csrf();
|
||||
$action = $_POST['action'] ?? '';
|
||||
|
||||
if ($action === 'create' || $action === 'update') {
|
||||
$id = $action === 'update' ? (int) ($_POST['id'] ?? 0) : 0;
|
||||
try {
|
||||
webhook_save($pdo, $id, [
|
||||
'name' => $_POST['name'] ?? '', 'url' => $_POST['url'] ?? '', 'secret' => $_POST['secret'] ?? '',
|
||||
'is_active' => ($_POST['status'] ?? 'active') === 'active', 'events' => $_POST['events'] ?? [],
|
||||
]);
|
||||
audit_log($staff['id'], ($action === 'create' ? 'Webhook erstellt: ' : 'Webhook aktualisiert: ') . trim($_POST['name'] ?? ''));
|
||||
flash('success', $action === 'create' ? 'Webhook erstellt.' : 'Änderungen gespeichert.');
|
||||
redirect('/staff/webhooks.php');
|
||||
} catch (AdminModelException $e) {
|
||||
$errors[] = $e->getMessage();
|
||||
}
|
||||
}
|
||||
if ($action === 'delete') {
|
||||
$pdo->prepare('DELETE FROM webhooks WHERE id = ?')->execute([(int) $_POST['id']]);
|
||||
audit_log($staff['id'], 'Webhook gelöscht: #' . (int) $_POST['id']);
|
||||
flash('success', 'Webhook gelöscht.');
|
||||
redirect('/staff/webhooks.php');
|
||||
}
|
||||
if ($action === 'test') {
|
||||
$hook = $pdo->prepare('SELECT * FROM webhooks WHERE id = ?');
|
||||
$hook->execute([(int) $_POST['id']]);
|
||||
if ($row = $hook->fetch()) {
|
||||
$payload = ['event' => 'test', 'occurredAt' => gmdate('c'), 'message' => 'Test-Ereignis von DeskHub'];
|
||||
[$status, $error] = webhook_deliver($row, $payload);
|
||||
$error === null ? flash('success', "Test erfolgreich zugestellt (HTTP {$status}).") : flash('error', 'Test fehlgeschlagen: ' . $error);
|
||||
}
|
||||
redirect('/staff/webhooks.php?edit=' . (int) $_POST['id']);
|
||||
}
|
||||
if ($action === 'reactivate') {
|
||||
$pdo->prepare('UPDATE webhooks SET is_active = 1, fail_count = 0 WHERE id = ?')->execute([(int) $_POST['id']]);
|
||||
redirect('/staff/webhooks.php');
|
||||
}
|
||||
}
|
||||
|
||||
$isNew = isset($_GET['new']);
|
||||
$editId = (int) ($_GET['edit'] ?? 0);
|
||||
$showForm = $isNew || $editId || ($errors && in_array($_POST['action'] ?? '', ['create', 'update'], true));
|
||||
$hooks = $pdo->query('SELECT * FROM webhooks ORDER BY name')->fetchAll();
|
||||
$editHook = null;
|
||||
if ($editId) {
|
||||
$stmt = $pdo->prepare('SELECT * FROM webhooks WHERE id = ?');
|
||||
$stmt->execute([$editId]);
|
||||
$editHook = $stmt->fetch() ?: null;
|
||||
}
|
||||
|
||||
$pageTitle = 'Webhooks';
|
||||
$activePage = 'webhooks';
|
||||
require __DIR__ . '/_header.php';
|
||||
?>
|
||||
|
||||
<?php foreach ($errors as $err): ?><div class="flash error"><?= e($err) ?></div><?php endforeach; ?>
|
||||
|
||||
<?php if ($showForm): ?>
|
||||
<?php
|
||||
$f = fn(string $k, $default = '') => $_POST[$k] ?? $default;
|
||||
$v = fn(string $k, string $col, $default = '') => $f($k, $editHook[$col] ?? $default);
|
||||
$curActive = $_POST ? (($_POST['status'] ?? 'active') === 'active') : (bool) ($editHook['is_active'] ?? 1);
|
||||
$curEvents = $_POST ? (array) ($_POST['events'] ?? []) : ($editHook ? explode(',', $editHook['events']) : array_keys($eventLabels));
|
||||
?>
|
||||
<h1>
|
||||
<?= $editHook ? 'Webhook aktualisieren' : 'Neuer Webhook' ?>
|
||||
<?php if ($editHook): ?><span class="muted" style="font-size:1rem;font-weight:400">— <?= e($editHook['name']) ?></span><?php endif; ?>
|
||||
</h1>
|
||||
|
||||
<form method="post" class="card" style="padding:0" autocomplete="off">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="action" value="<?= $editHook ? 'update' : 'create' ?>">
|
||||
<?php if ($editHook): ?><input type="hidden" name="id" value="<?= (int) $editHook['id'] ?>"><?php endif; ?>
|
||||
|
||||
<?php ui_tab_bar(['hook' => 'Webhook', 'events' => 'Ereignisse']); ?>
|
||||
|
||||
<div class="tab-pane" data-pane="hook" style="padding:16px 20px">
|
||||
<h3 style="margin-top:0">Ziel</h3>
|
||||
<label for="name">Name *</label>
|
||||
<input type="text" id="name" name="name" value="<?= e($v('name', 'name')) ?>" placeholder="z. B. Slack-Benachrichtigung" required>
|
||||
<label for="url">URL *</label>
|
||||
<input type="url" id="url" name="url" value="<?= e($v('url', 'url')) ?>" placeholder="https://example.de/hooks/deskhub" required>
|
||||
<label for="secret">Geheimnis zum Signieren</label>
|
||||
<input type="password" id="secret" name="secret" placeholder="<?= $editHook ? '(unverändert)' : 'leer = wird automatisch erzeugt' ?>" autocomplete="new-password">
|
||||
<p class="muted" style="font-size:.8rem">Jede Zustellung enthält den Header <code>X-DeskHub-Signature: sha256=…</code> (HMAC-SHA256 des Körpers mit diesem Geheimnis), damit dein System die Herkunft prüfen kann.</p>
|
||||
<?php ui_status_radios($curActive); ?>
|
||||
<?php if ($editHook): ?>
|
||||
<p class="muted" style="font-size:.82rem">
|
||||
Letzte Zustellung: <?= e(cron_last_run_label($editHook['last_delivery_at'] ?? null)) ?>
|
||||
<?= $editHook['last_status'] ? ' · HTTP ' . (int) $editHook['last_status'] : '' ?>
|
||||
<?= $editHook['last_error'] ? ' · <span style="color:#dc2626">' . e($editHook['last_error']) . '</span>' : '' ?>
|
||||
<?= (int) $editHook['fail_count'] > 0 ? ' · ' . (int) $editHook['fail_count'] . ' Fehler in Folge (nach 10 wird der Webhook automatisch deaktiviert)' : '' ?>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div class="tab-pane" data-pane="events" style="padding:16px 20px;display:none">
|
||||
<h3 style="margin-top:0">Ereignisse</h3>
|
||||
<?php foreach ($eventLabels as $key => $label): ?>
|
||||
<label style="display:flex;align-items:center;gap:8px;font-weight:400;margin:6px 0">
|
||||
<input type="checkbox" name="events[]" value="<?= e($key) ?>" style="width:auto" <?= in_array($key, $curEvents, true) ? 'checked' : '' ?>>
|
||||
<?= e($label) ?> <code class="muted"><?= e($key) ?></code>
|
||||
</label>
|
||||
<?php endforeach; ?>
|
||||
<p class="muted" style="font-size:.82rem;margin-top:12px">Der Körper ist JSON mit <code>event</code>, <code>occurredAt</code> und den Ticketdaten (Nummer, Betreff, Status, Priorität, Abteilung, Anfragender).</p>
|
||||
</div>
|
||||
|
||||
<div class="btn-row" style="padding:0 20px 18px">
|
||||
<button type="submit" class="btn"><?= $editHook ? 'Änderungen speichern' : 'Erstellen' ?></button>
|
||||
<a href="/staff/webhooks.php" class="btn secondary">Abbrechen</a>
|
||||
</div>
|
||||
</form>
|
||||
<?php if ($editHook): ?>
|
||||
<form method="post" style="margin-top:10px"><?= csrf_field() ?><input type="hidden" name="action" value="test"><input type="hidden" name="id" value="<?= (int) $editHook['id'] ?>">
|
||||
<button type="submit" class="btn secondary">Test-Ereignis senden</button> <span class="muted" style="font-size:.8rem">(verwendet die gespeicherten Werte)</span></form>
|
||||
<?php endif; ?>
|
||||
<?php ui_tab_assets('hook'); ?>
|
||||
|
||||
<?php else: ?>
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;gap:12px">
|
||||
<h1 style="margin:0">Webhooks</h1>
|
||||
<a href="/staff/webhooks.php?new=1" class="btn">Neuen Webhook hinzufügen</a>
|
||||
</div>
|
||||
<p class="muted">DeskHub meldet Ereignisse (Ticket erstellt, beantwortet, Status geändert, zugewiesen) per HTTP-POST an die hinterlegten URLs – z. B. für Chat-Benachrichtigungen oder Ihr eigenes System. Tickets von außen anlegen: <a href="/staff/api_keys.php">API-Schlüssel</a>.</p>
|
||||
|
||||
<div class="card">
|
||||
<table>
|
||||
<thead><tr><th>Name</th><th>URL</th><th>Ereignisse</th><th>Status</th><th>Letzte Zustellung</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($hooks as $h): ?>
|
||||
<tr>
|
||||
<td><a href="/staff/webhooks.php?edit=<?= (int) $h['id'] ?>"><?= e($h['name']) ?></a></td>
|
||||
<td class="muted" style="font-size:.82rem;word-break:break-all"><?= e($h['url']) ?></td>
|
||||
<td style="font-size:.8rem"><?= e(implode(', ', array_map(fn($k) => $eventLabels[$k] ?? $k, explode(',', $h['events'])))) ?></td>
|
||||
<td><strong><?= $h['is_active'] ? 'Aktiv' : 'Deaktiviert' ?></strong><?= !$h['is_active'] && (int) $h['fail_count'] >= 10 ? '<div class="muted" style="font-size:.74rem">wegen Fehlern abgeschaltet</div>' : '' ?></td>
|
||||
<td class="muted" style="font-size:.82rem"><?= e(cron_last_run_label($h['last_delivery_at'] ?? null)) ?><?= $h['last_error'] ? '<div style="color:#dc2626">' . e($h['last_error']) . '</div>' : ($h['last_status'] ? ' · HTTP ' . (int) $h['last_status'] : '') ?></td>
|
||||
<td style="white-space:nowrap">
|
||||
<a href="/staff/webhooks.php?edit=<?= (int) $h['id'] ?>">Bearbeiten</a>
|
||||
<?php if (!$h['is_active']): ?> · <form method="post" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="reactivate"><input type="hidden" name="id" value="<?= (int) $h['id'] ?>"><button type="submit" style="background:none;border:none;color:var(--primary);cursor:pointer;padding:0;font-size:.9rem">Aktivieren</button></form><?php endif; ?> ·
|
||||
<form method="post" style="display:inline" onsubmit="return confirm('Webhook löschen?')"><?= csrf_field() ?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= (int) $h['id'] ?>">
|
||||
<button type="submit" style="background:none;border:none;color:#dc2626;cursor:pointer;padding:0;font-size:.9rem">Löschen</button></form>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php if (!$hooks): ?><tr><td colspan="6" class="muted">Noch keine Webhooks angelegt.</td></tr><?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php require __DIR__ . '/_footer.php'; ?>
|
||||
Reference in New Issue
Block a user