diff --git a/backup/image-hoster/admin.html b/backup/image-hoster/admin.html new file mode 100644 index 0000000..ed96b0b --- /dev/null +++ b/backup/image-hoster/admin.html @@ -0,0 +1,206 @@ + + + + + + Admin Panel - Host-It-Live Pro + + + + +
+ +
+

Admin Access

+ + + +
+ + +
+
+

Server Overview

+ +
+ +
+
+
0
+
Active Sessions
+
+
+
0
+
Total Requests
+
+
+
0 MB
+
Data Transferred
+
+
+ + + + + + + + + + + + + +
IDModeCreatedIP / User AgentTrafficTunnel / Path
+
+
+ + + + diff --git a/backup/image-hoster/index.html b/backup/image-hoster/index.html new file mode 100644 index 0000000..c02cf8a --- /dev/null +++ b/backup/image-hoster/index.html @@ -0,0 +1,1127 @@ + + + + + + Host It Now + + + + + +
+ +
+ + +
+
+ + Host It Now +
+ +
+ + +
+ Sessions +
+ + +
+ + +
+
+
+ + Live Public Link + + Offline + +
+
+ + + +
+
+ + +
+ + +
+
+
+ + Host Your Content +
+
+
+ + + +
+ + +
+ +
+ + +
+ +
+ + No active source — pick a folder or enter a server path. +
+
+
+ + +
+ +
+ + + + diff --git a/cmd/image-hoster/main.go b/cmd/image-hoster/main.go index a0e9f44..31431b4 100644 --- a/cmd/image-hoster/main.go +++ b/cmd/image-hoster/main.go @@ -57,12 +57,28 @@ func main() { r.Get("/", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, filepath.Join(webDir, "index.html")) }) + r.Get("/styles.css", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/css; charset=utf-8") + http.ServeFile(w, r, filepath.Join(webDir, "styles.css")) + }) + r.Get("/app.js", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/javascript; charset=utf-8") + http.ServeFile(w, r, filepath.Join(webDir, "app.js")) + }) r.Get("/radheradhe", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, filepath.Join(webDir, "admin.html")) }) r.Get("/radheradhe/", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, filepath.Join(webDir, "admin.html")) }) + r.Get("/admin.css", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/css; charset=utf-8") + http.ServeFile(w, r, filepath.Join(webDir, "admin.css")) + }) + r.Get("/admin.js", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/javascript; charset=utf-8") + http.ServeFile(w, r, filepath.Join(webDir, "admin.js")) + }) r.Post("/create_session", func(w http.ResponseWriter, r *http.Request) { var req struct { diff --git a/web/image-hoster/admin.css b/web/image-hoster/admin.css new file mode 100644 index 0000000..ba27482 --- /dev/null +++ b/web/image-hoster/admin.css @@ -0,0 +1,87 @@ +:root { + --bg-color: #0f0f13; + --card-bg: #1a1a20; + --accent: #7b2cbf; + --accent-glow: #9d4edd; + --text-main: #e0e0e0; + --success: #06d6a0; + --danger: #ef476f; + } + body { + background: var(--bg-color); + color: var(--text-main); + font-family: 'Segoe UI', system-ui, sans-serif; + display: flex; + flex-direction: column; + align-items: center; + padding: 40px; + margin: 0; + min-height: 100vh; + } + .container { width: 100%; max-width: 900px; } + + /* Login */ + #loginPanel { + max-width: 400px; + margin: 100px auto; + background: var(--card-bg); + padding: 40px; + border-radius: 12px; + text-align: center; + box-shadow: 0 0 30px rgba(123, 44, 191, 0.2); + border: 1px solid rgba(123, 44, 191, 0.3); + } + input { + width: 100%; + padding: 12px; + margin: 15px 0; + background: rgba(0,0,0,0.3); + border: 1px solid #333; + color: white; + border-radius: 6px; + } + button { + width: 100%; + padding: 12px; + background: var(--accent); + color: white; + border: none; + border-radius: 6px; + cursor: pointer; + font-weight: bold; + transition: 0.2s; + } + button:hover { background: var(--accent-glow); transform: scale(1.02); } + + /* Dashboard */ + #dashboard { display: none; width: 100%; animation: fadeIn 0.5s ease; } + @keyframes fadeIn { from { opacity:0; transform:translateY(10px); } to { opacity:1; transform:translateY(0); } } + + .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; } + .stat-card { + background: var(--card-bg); + padding: 20px; + border-radius: 10px; + display: inline-block; + width: 30%; + margin-right: 2%; + text-align: center; + box-shadow: 0 4px 15px rgba(0,0,0,0.2); + } + .stat-value { font-size: 2rem; font-weight: bold; color: var(--accent-glow); } + + table { width: 100%; border-collapse: collapse; margin-top: 20px; background: var(--card-bg); border-radius: 10px; overflow: hidden; } + th, td { padding: 15px; text-align: left; border-bottom: 1px solid #333; } + th { background: rgba(123, 44, 191, 0.2); text-transform: uppercase; font-size: 0.8rem; letter-spacing: 1px; } + tr:hover { background: rgba(255,255,255,0.02); } + .badge { padding: 4px 8px; border-radius: 12px; font-size: 0.75rem; font-weight: bold; } + .bg-relay { background: rgba(6, 214, 160, 0.2); color: var(--success); } + .bg-host { background: rgba(255, 209, 102, 0.2); color: #ffd166; } + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} diff --git a/web/image-hoster/admin.html b/web/image-hoster/admin.html index ed96b0b..389940f 100644 --- a/web/image-hoster/admin.html +++ b/web/image-hoster/admin.html @@ -5,87 +5,7 @@ Admin Panel - Host-It-Live Pro - +
@@ -135,72 +55,7 @@
- + diff --git a/web/image-hoster/admin.js b/web/image-hoster/admin.js new file mode 100644 index 0000000..e9cae21 --- /dev/null +++ b/web/image-hoster/admin.js @@ -0,0 +1,65 @@ +let adminPwd = ''; + + async function login() { + const pwd = document.getElementById('pwd').value; + const res = await fetch('/admin_login', { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ password: pwd }) + }); + const data = await res.json(); + if(data.success) { + adminPwd = pwd; + document.getElementById('loginPanel').style.display = 'none'; + document.getElementById('dashboard').style.display = 'block'; + loadStats(); + setInterval(loadStats, 5000); // Auto refresh + } else { + document.getElementById('errorMsg').style.display = 'block'; + } + } + + async function loadStats() { + const res = await fetch('/admin_stats', { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ password: adminPwd }) + }); + const data = await res.json(); + if(data.success) { + // Update Cards + document.getElementById('totalSessions').innerText = data.sessions.length; + const reqs = data.sessions.reduce((a, b) => a + b.requests, 0); + const bytes = data.sessions.reduce((a, b) => a + b.bytes, 0); + document.getElementById('totalReqs').innerText = reqs; + document.getElementById('totalBytes').innerText = (bytes / 1024 / 1024).toFixed(2) + " MB"; + + // Update Table + const tbody = document.querySelector('#sessionTable tbody'); + tbody.innerHTML = ''; + data.sessions.forEach(s => { + const row = document.createElement('tr'); + const modeClass = s.mode === 'Relay' ? 'bg-relay' : 'bg-host'; + const uaShort = s.ua.length > 30 ? s.ua.substring(0, 30) + '...' : s.ua; + const tunnelHtml = s.tunnel_active ? `
${s.tunnel_url}
` : `
Offline
`; + row.innerHTML = ` + ${s.id} + ${s.mode} + ${s.created} + +
${s.ip}
+
${uaShort}
+ + +
${s.requests} reqs
+
${(s.bytes/1024).toFixed(1)} KB
+ + + ${tunnelHtml} +
Path: ${s.path}
+ + `; + tbody.appendChild(row); + }); + } + } diff --git a/web/image-hoster/app.js b/web/image-hoster/app.js new file mode 100644 index 0000000..4bc19cf --- /dev/null +++ b/web/image-hoster/app.js @@ -0,0 +1,509 @@ +// ───────────────────────────────────────────── +// Derive gateway prefix so file links work through the proxy. +// If we're at /tool/image-hoster/ → TOOL_BASE = "/tool/image-hoster" +// If we're at / → TOOL_BASE = "" +const TOOL_BASE = (() => { + const p = window.location.pathname.replace(/\/+$/, ''); + // pathname ends with the tool slug; anything before it that looks like /tool/X is the prefix + return p; +})(); + +// ───────────────────────────────────────────── +// State +// ───────────────────────────────────────────── +let sessions = []; +try { + sessions = JSON.parse(localStorage.getItem('hin_sessions')) || []; + if (!Array.isArray(sessions)) sessions = []; + // Purge broken sessions + sessions = sessions.filter(s => s && s.id && s.id !== 'undefined' && s.id !== 'null'); +} catch(e) { sessions = []; } + +let currentId = localStorage.getItem('hin_current'); +if (currentId === 'undefined' || currentId === 'null') currentId = null; +if (currentId && !sessions.find(s => s.id === currentId)) currentId = null; + +const relayFiles = {}; // sessionId -> { path: File } +const evtSources = {}; // sessionId -> EventSource +const tunnelInfo = {}; // sessionId -> { url, active } + +// ───────────────────────────────────────────── +// Boot +// ───────────────────────────────────────────── +async function init() { + save(); + if (!sessions.length) { + await createNewSession(); + } else { + if (!currentId) currentId = sessions[0].id; + renderSessionTabs(); + loadSession(currentId); + } +} + +// ───────────────────────────────────────────── +// Session Management +// ───────────────────────────────────────────── +async function createNewSession() { + try { + const res = await fetch('/create_session', { method: 'POST' }); + const data = await res.json(); + if (data.success) { + const sid = data.session_id; + sessions.push({ id: sid, created: Date.now() }); + save(); + switchSession(sid); + } else { + toast('Failed to create session', true); + } + } catch(e) { toast('Server error: ' + e.message, true); } +} + +async function deleteSession() { + if (!currentId) return; + if (!confirm('Delete this session and all its hosted content?')) return; + + // Tell server + await fetch('/delete_session', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session_id: currentId }) + }).catch(() => {}); + + // Clean up client state + if (evtSources[currentId]) { evtSources[currentId].close(); delete evtSources[currentId]; } + delete relayFiles[currentId]; + delete tunnelInfo[currentId]; + + sessions = sessions.filter(s => s.id !== currentId); + currentId = null; + save(); + + if (sessions.length) { + switchSession(sessions[0].id); + } else { + await createNewSession(); + } + toast('Session deleted'); +} + +function switchSession(id) { + currentId = id; + localStorage.setItem('hin_current', id); + renderSessionTabs(); + resetUI(); + loadSession(id); +} + +function save() { + localStorage.setItem('hin_sessions', JSON.stringify(sessions)); + if (currentId) localStorage.setItem('hin_current', currentId); +} + +function renderSessionTabs() { + const container = document.getElementById('sessionTabs'); + container.innerHTML = ''; + sessions.forEach(s => { + const tab = document.createElement('div'); + tab.className = 'session-tab' + (s.id === currentId ? ' active' : ''); + tab.textContent = 'S-' + s.id.slice(-6).toUpperCase(); + tab.title = s.id; + tab.onclick = () => switchSession(s.id); + container.appendChild(tab); + }); +} + +// ───────────────────────────────────────────── +// Load a session +// ───────────────────────────────────────────── +async function loadSession(sid) { + connectSSE(sid); + checkTunnel(sid); + + // Load files from server + try { + const res = await fetch(`/get_session_files/${sid}`); + const data = await res.json(); + if (sid !== currentId) return; + + if (data.mode === 'relay') { + setStatus('Browser Relay mode — files served from your device', true); + } else if (data.path_set && data.files && data.files.length) { + setStatus(`📂 ${data.current_path}`, true); + // Normalize server-returned URLs: server gives /files//..., + // we need TOOL_BASE + /files//... so the gateway proxies correctly + const normalised = data.files.map(f => ({ + ...f, + url: f.url.startsWith(TOOL_BASE) ? f.url : TOOL_BASE + f.url, + })); + renderFileGroups(normalised); + } else if (data.path_set) { + setStatus(`📂 ${data.current_path} (empty)`, true); + } else { + resetUI(); + } + } catch(e) { /* ignore */ } +} + +function resetUI() { + setStatus('No active source — pick a folder or enter a server path.', false); + document.getElementById('filesSection').innerHTML = ''; + document.getElementById('pathInput').value = ''; + setTunnelUI(false); +} + +// ───────────────────────────────────────────── +// File Hosting +// ───────────────────────────────────────────── +async function handleFileSelect(evt, type) { + const files = evt.target.files; + if (!files.length) return; + + if (!relayFiles[currentId]) relayFiles[currentId] = {}; + const map = relayFiles[currentId]; + + for (const f of files) { + const key = type === 'folder' ? (f.webkitRelativePath || f.name) : f.name; + map[key] = f; + } + + // Tell server we're in relay mode + await fetch('/set_session_path', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session_id: currentId, path: '(Relay Mode)' }) + }).catch(() => {}); + + setStatus(`Browser relay active — ${Object.keys(map).length} file(s) queued`, true); + + // Build file list for display using TOOL_BASE so links route through the gateway + const fileList = Object.entries(map).map(([path, f]) => ({ + name: f.name, + path: path, + url: `${TOOL_BASE}/files/${currentId}/${path}`, + folder: path.includes('/') ? path.split('/').slice(0, -1).join('/') : '(Root)', + is_code: /\.(json|html?|css|js)$/i.test(f.name), + })); + renderFileGroups(fileList); + connectSSE(currentId); + + // Reset input + evt.target.value = ''; + toast(`${files.length} file(s) queued for hosting`); +} + +async function setFolderPath() { + const path = document.getElementById('pathInput').value.trim(); + if (!path) return toast('Enter a path first', true); + + const res = await fetch('/set_session_path', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session_id: currentId, path }) + }).catch(() => null); + + if (!res || !res.ok) return toast('Server error', true); + const data = await res.json(); + + if (data.success) { + toast('Path mapped successfully'); + delete relayFiles[currentId]; + setStatus(`📂 ${path}`, true); + // reload files + const r2 = await fetch(`/get_session_files/${currentId}`).catch(() => null); + if (r2) { + const d2 = await r2.json(); + if (d2.files && d2.files.length) renderFileGroups(d2.files); + } + } else { + toast(data.error || 'Failed to set path', true); + } +} + +// ───────────────────────────────────────────── +// Server-Sent Events (Relay mode) +// ───────────────────────────────────────────── +function connectSSE(sid) { + if (evtSources[sid]) return; + // Use TOOL_BASE so the SSE URL goes through the gateway proxy correctly. + // The gateway shim also patches EventSource, but this is a direct safety net. + const es = new EventSource(`${TOOL_BASE}/stream_events/${sid}`); + es.onmessage = async (e) => { + if (!e.data) return; + try { + const msg = JSON.parse(e.data); + if (msg.type === 'request_file') await fulfillRelay(sid, msg.req_id, msg.filename); + } catch(err) {} + }; + evtSources[sid] = es; +} + +async function fulfillRelay(sid, reqId, filename) { + const map = relayFiles[sid] || {}; + const file = map[filename]; + const fd = new FormData(); + fd.append('req_id', reqId); + if (file) fd.append('file', file); + await fetch('/fulfill_request', { method: 'POST', body: fd }).catch(() => {}); +} + +// ───────────────────────────────────────────── +// Tunnel / Live Link +// ───────────────────────────────────────────── +async function startTunnel() { + const sid = currentId; + document.getElementById('btnGoLive').classList.add('hidden'); + document.getElementById('liveSpinner').classList.remove('hidden'); + + try { + const res = await fetch('/get_tunnel', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session_id: sid }) + }); + const data = await res.json(); + if (data.success) { + tunnelInfo[sid] = { url: data.url, active: true }; + if (currentId === sid) setTunnelUI(true, data.url); + toast('Live! Link is ready.'); + } else { + toast(data.error || 'Failed to go live', true); + if (currentId === sid) setTunnelUI(false); + } + } catch(e) { + toast('Error: ' + e.message, true); + if (currentId === sid) setTunnelUI(false); + } finally { + document.getElementById('liveSpinner').classList.add('hidden'); + } +} + +async function stopTunnel() { + const sid = currentId; + await fetch('/stop_tunnel', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session_id: sid }) + }).catch(() => {}); + if (tunnelInfo[sid]) tunnelInfo[sid].active = false; + if (currentId === sid) setTunnelUI(false); + toast('Tunnel stopped'); +} + +async function regenerateTunnel() { + const sid = currentId; + await fetch('/regenerate_tunnel', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session_id: sid }) + }).catch(() => {}); + if (tunnelInfo[sid]) tunnelInfo[sid].active = false; + setTunnelUI(false); + setTimeout(startTunnel, 500); +} + +async function checkTunnel(sid) { + try { + const res = await fetch('/get_tunnel_status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session_id: sid }) + }); + const data = await res.json(); + if (data.active && currentId === sid) { + tunnelInfo[sid] = { url: data.url, active: true }; + setTunnelUI(true, data.url); + } + } catch(e) {} +} + +function setTunnelUI(active, url) { + const panel = document.getElementById('livePanel'); + const badge = document.getElementById('liveBadge'); + const goLive = document.getElementById('btnGoLive'); + const stop = document.getElementById('btnStopLive'); + const urlRow = document.getElementById('liveUrlRow'); + const urlText = document.getElementById('liveUrlText'); + const openBtn = document.getElementById('liveOpenBtn'); + + if (active) { + panel.classList.add('is-live'); + badge.className = 'badge badge-live'; + badge.innerHTML = ' Live'; + goLive.classList.add('hidden'); + stop.classList.remove('hidden'); + urlRow.classList.remove('hidden'); + urlText.textContent = url; + openBtn.href = url; + } else { + panel.classList.remove('is-live'); + badge.className = 'badge badge-offline'; + badge.innerHTML = ' Offline'; + goLive.classList.remove('hidden'); + stop.classList.add('hidden'); + urlRow.classList.add('hidden'); + document.getElementById('liveSpinner').classList.add('hidden'); + } +} + +function copyLiveUrl() { + const url = document.getElementById('liveUrlText').textContent; + navigator.clipboard.writeText(url).then(() => toast('Copied!')).catch(() => { + const t = document.createElement('textarea'); + t.value = url; + document.body.appendChild(t); + t.select(); + document.execCommand('copy'); + document.body.removeChild(t); + toast('Copied!'); + }); +} + +// ───────────────────────────────────────────── +// Render Files +// ───────────────────────────────────────────── +function renderFileGroups(files) { + const container = document.getElementById('filesSection'); + container.innerHTML = ''; + + if (!files || !files.length) { + container.innerHTML = `
+ +

No files in this session yet.

+
`; + return; + } + + const groups = {}; + files.forEach(f => { + const key = f.folder || '(Root)'; + if (!groups[key]) groups[key] = []; + groups[key].push(f); + }); + + const tInfo = tunnelInfo[currentId]; + const isLiveTunnel = tInfo && tInfo.active; + + // Local base — use TOOL_BASE so gateway proxy routes correctly + // e.g. /tool/image-hoster/files//file.jpg + const localFileBase = `${TOOL_BASE}/files/${currentId}`; + + Object.keys(groups).sort().forEach(groupName => { + const groupFiles = groups[groupName]; + const relDir = groupName === '(Root)' ? '' : groupName; + + // ── Endpoint URL for the folder ── + let endpointUrl; + if (isLiveTunnel && tInfo.url.includes('/hoster/')) { + // Custom nexus domain already embeds session ID + endpointUrl = relDir ? `${tInfo.url}/${relDir}/` : `${tInfo.url}/`; + } else if (isLiveTunnel) { + endpointUrl = relDir + ? `${tInfo.url}/files/${currentId}/${relDir}/` + : `${tInfo.url}/files/${currentId}/`; + } else { + endpointUrl = relDir + ? `${window.location.origin}${localFileBase}/${relDir}/` + : `${window.location.origin}${localFileBase}/`; + } + endpointUrl = endpointUrl.replace(/([^:])\/\/+/g, '$1/'); + + const card = document.createElement('div'); + card.className = 'card folder-group'; + + let html = ` +
+
+ + ${groupName} +
+ ${groupFiles.length} file${groupFiles.length !== 1 ? 's' : ''} +
+
+ + ${endpointUrl} + +
`; + + const shown = groupFiles.slice(0, 8); + shown.forEach(f => { + // ── Per-file URL ── + let fileUrl; + if (isLiveTunnel && tInfo.url.includes('/hoster/')) { + fileUrl = `${tInfo.url}/${f.path || f.name}`.replace(/([^:])\/\/+/g, '$1/'); + } else if (isLiveTunnel) { + fileUrl = `${tInfo.url}/files/${currentId}/${f.path || f.name}`; + } else { + // Use TOOL_BASE so the link is e.g. /tool/image-hoster/files//img.jpg + fileUrl = `${localFileBase}/${f.path || f.name}`.replace(/([^:])\/\/+/g, '$1/'); + } + + const isImg = /\.(jpe?g|png|gif|webp|svg|bmp|ico)$/i.test(f.name); + + html += ` +
+ ${isImg + ? `` + : '' + } +
+ +
+ ${f.name} + + + + +
`; + }); + + if (groupFiles.length > 8) { + html += `
+ + ${groupFiles.length - 8} more files +
`; + } + + card.innerHTML = html; + container.appendChild(card); + }); +} + +// ───────────────────────────────────────────── +// Helpers +// ───────────────────────────────────────────── +function setStatus(msg, active) { + const bar = document.getElementById('statusBar'); + const txt = document.getElementById('statusText'); + txt.textContent = msg; + bar.className = 'status-bar' + (active ? ' has-source' : ''); +} + +function copyText(text) { + navigator.clipboard.writeText(text).then(() => toast('Copied!')).catch(() => { + const t = document.createElement('textarea'); + t.value = text; + document.body.appendChild(t); + t.select(); + document.execCommand('copy'); + document.body.removeChild(t); + toast('Copied!'); + }); +} + +let toastTimer; +function toast(msg, isErr = false) { + const el = document.getElementById('toast'); + el.textContent = msg; + el.className = 'show ' + (isErr ? 'error' : 'success'); + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { el.className = ''; }, 2500); +} + +// ───────────────────────────────────────────── +// Boot +// ───────────────────────────────────────────── +init(); diff --git a/web/image-hoster/index.html b/web/image-hoster/index.html index c02cf8a..ce52672 100644 --- a/web/image-hoster/index.html +++ b/web/image-hoster/index.html @@ -5,497 +5,7 @@ Host It Now - + @@ -612,516 +122,7 @@ - + diff --git a/web/image-hoster/styles.css b/web/image-hoster/styles.css new file mode 100644 index 0000000..5fa7224 --- /dev/null +++ b/web/image-hoster/styles.css @@ -0,0 +1,504 @@ +:root { + --bg: #0b0b10; + --surface: #13131a; + --surface2: #1c1c28; + --border: rgba(255,255,255,0.07); + --primary: #7c3aed; + --primary-dim: rgba(124,58,237,0.15); + --cyan: #22d3ee; + --cyan-dim: rgba(34,211,238,0.12); + --green: #10b981; + --green-dim: rgba(16,185,129,0.15); + --pink: #f43f5e; + --pink-dim: rgba(244,63,94,0.15); + --text: #f1f5f9; + --muted: #64748b; + --radius: 12px; + --transition: 0.2s ease; + } + + * { box-sizing: border-box; margin: 0; padding: 0; } + + body { + background: var(--bg); + color: var(--text); + font-family: 'Segoe UI', system-ui, sans-serif; + min-height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + padding: 24px 16px 60px; + } + + .app { + width: 100%; + max-width: 860px; + display: flex; + flex-direction: column; + gap: 16px; + } + + /* ─── Topbar ─── */ + .topbar { + display: flex; + align-items: center; + justify-content: space-between; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 14px 20px; + } + + .topbar-brand { + display: flex; + align-items: center; + gap: 10px; + font-size: 1.25rem; + font-weight: 700; + color: var(--cyan); + } + + .topbar-brand i { font-size: 1.1rem; } + + .topbar-right { + display: flex; + align-items: center; + gap: 8px; + } + + /* ─── Buttons ─── */ + .btn { + display: inline-flex; + align-items: center; + gap: 7px; + padding: 9px 16px; + border-radius: 8px; + border: 1px solid var(--border); + background: var(--surface2); + color: var(--text); + font-size: 0.875rem; + font-weight: 600; + cursor: pointer; + transition: var(--transition); + text-decoration: none; + white-space: nowrap; + } + + .btn:hover { background: rgba(255,255,255,0.08); border-color: rgba(255,255,255,0.15); } + .btn:active { transform: scale(0.97); } + + .btn-primary { + background: var(--primary); + border-color: transparent; + box-shadow: 0 0 16px rgba(124,58,237,0.4); + } + .btn-primary:hover { background: #6d28d9; box-shadow: 0 0 22px rgba(124,58,237,0.55); } + + .btn-cyan { + background: var(--cyan-dim); + border-color: rgba(34,211,238,0.25); + color: var(--cyan); + } + .btn-cyan:hover { background: rgba(34,211,238,0.2); } + + .btn-green { + background: var(--green-dim); + border-color: rgba(16,185,129,0.3); + color: var(--green); + } + .btn-green:hover { background: rgba(16,185,129,0.25); } + + .btn-danger { + background: var(--pink-dim); + border-color: rgba(244,63,94,0.3); + color: var(--pink); + } + .btn-danger:hover { background: rgba(244,63,94,0.25); } + + .btn-icon { padding: 9px 11px; } + .btn-sm { padding: 6px 12px; font-size: 0.8rem; } + + /* ─── Session Bar ─── */ + .session-bar { + display: flex; + align-items: center; + gap: 8px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 12px 16px; + } + + .session-label { + font-size: 0.75rem; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--muted); + flex-shrink: 0; + } + + .session-tabs { + display: flex; + gap: 6px; + flex-wrap: wrap; + flex: 1; + } + + .session-tab { + padding: 5px 12px; + border-radius: 20px; + border: 1px solid var(--border); + background: var(--surface2); + color: var(--muted); + font-size: 0.8rem; + font-weight: 600; + cursor: pointer; + transition: var(--transition); + } + + .session-tab:hover { border-color: rgba(255,255,255,0.2); color: var(--text); } + .session-tab.active { + background: var(--primary-dim); + border-color: rgba(124,58,237,0.5); + color: #c4b5fd; + } + + /* ─── Card ─── */ + .card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + overflow: hidden; + } + + .card-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 16px 20px; + border-bottom: 1px solid var(--border); + } + + .card-title { + display: flex; + align-items: center; + gap: 10px; + font-size: 0.95rem; + font-weight: 700; + } + + .card-body { padding: 20px; } + + /* ─── Live Link Panel ─── */ + .live-panel { + border-color: var(--border); + } + + .live-panel.is-live { + border-color: rgba(16,185,129,0.4); + background: linear-gradient(135deg, var(--surface), rgba(16,185,129,0.04)); + } + + .badge { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 3px 10px; + border-radius: 20px; + font-size: 0.7rem; + font-weight: 800; + letter-spacing: 0.08em; + text-transform: uppercase; + } + + .badge-offline { + background: rgba(255,255,255,0.06); + color: var(--muted); + } + + .badge-live { + background: var(--green-dim); + color: var(--green); + border: 1px solid rgba(16,185,129,0.3); + animation: pulse-badge 2s infinite; + } + + @keyframes pulse-badge { + 0%, 100% { box-shadow: 0 0 0 0 rgba(16,185,129,0.4); } + 50% { box-shadow: 0 0 0 5px rgba(16,185,129,0); } + } + + .live-url-box { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 14px; + background: var(--surface2); + border: 1px solid rgba(34,211,238,0.2); + border-radius: 8px; + flex: 1; + } + + .live-url-text { + font-family: 'Consolas', 'Fira Code', monospace; + font-size: 0.9rem; + color: var(--cyan); + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .live-actions { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + } + + /* ─── Host Panel ─── */ + .host-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; + } + + .host-btn { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 10px; + padding: 24px; + border-radius: 10px; + border: 2px dashed rgba(255,255,255,0.1); + background: transparent; + color: var(--muted); + cursor: pointer; + transition: var(--transition); + font-size: 0.9rem; + font-weight: 600; + } + + .host-btn i { font-size: 1.8rem; } + .host-btn:hover { border-color: var(--cyan); color: var(--cyan); background: var(--cyan-dim); } + .host-btn.pink:hover { border-color: var(--pink); color: var(--pink); background: var(--pink-dim); } + + /* ─── Path Input ─── */ + .path-row { + display: flex; + gap: 8px; + margin-top: 12px; + } + + .input-field { + flex: 1; + background: var(--surface2); + border: 1px solid var(--border); + color: var(--text); + padding: 10px 14px; + border-radius: 8px; + font-size: 0.9rem; + transition: var(--transition); + } + + .input-field:focus { + outline: none; + border-color: rgba(34,211,238,0.4); + box-shadow: 0 0 0 3px rgba(34,211,238,0.08); + } + + .input-field::placeholder { color: var(--muted); } + + /* ─── Status Bar ─── */ + .status-bar { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 14px; + border-radius: 8px; + background: var(--surface2); + font-size: 0.875rem; + color: var(--muted); + margin-top: 12px; + min-height: 42px; + } + + .status-bar.has-source { color: var(--cyan); background: var(--cyan-dim); border: 1px solid rgba(34,211,238,0.2); } + + /* ─── Files Section ─── */ + .files-section { margin-top: 4px; } + + .folder-group { + border: 1px solid var(--border); + border-radius: var(--radius); + overflow: hidden; + margin-bottom: 12px; + } + + .folder-group-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 16px; + background: var(--surface2); + border-bottom: 1px solid var(--border); + } + + .folder-name { + display: flex; + align-items: center; + gap: 8px; + font-weight: 700; + font-size: 0.9rem; + } + + .count-badge { + padding: 2px 8px; + border-radius: 12px; + background: rgba(255,255,255,0.06); + color: var(--muted); + font-size: 0.75rem; + font-weight: 700; + } + + .endpoint-strip { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 16px; + background: rgba(0,0,0,0.25); + border-bottom: 1px solid var(--border); + } + + .endpoint-url { + font-family: monospace; + font-size: 0.82rem; + color: var(--cyan); + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .file-row { + display: flex; + align-items: center; + gap: 12px; + padding: 10px 16px; + border-bottom: 1px solid var(--border); + transition: background var(--transition); + } + + .file-row:last-child { border-bottom: none; } + .file-row:hover { background: rgba(255,255,255,0.03); } + + .file-thumb { + width: 36px; + height: 36px; + border-radius: 6px; + object-fit: cover; + flex-shrink: 0; + background: var(--surface2); + } + + .file-icon-placeholder { + width: 36px; + height: 36px; + border-radius: 6px; + background: var(--primary-dim); + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + } + + .file-icon-placeholder i { color: #c4b5fd; font-size: 0.9rem; } + + .file-name { + flex: 1; + font-size: 0.875rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .empty-state { + padding: 50px 20px; + text-align: center; + color: var(--muted); + } + + .empty-state i { font-size: 2.5rem; margin-bottom: 12px; opacity: 0.4; display: block; } + .empty-state p { font-size: 0.9rem; } + + /* ─── Spinner ─── */ + .spinner { + display: inline-block; + width: 16px; + height: 16px; + border: 2px solid rgba(255,255,255,0.2); + border-top-color: var(--cyan); + border-radius: 50%; + animation: spin 0.7s linear infinite; + } + + @keyframes spin { to { transform: rotate(360deg); } } + + /* ─── Toast ─── */ + #toast { + position: fixed; + bottom: 28px; + left: 50%; + transform: translateX(-50%) translateY(10px); + padding: 10px 24px; + border-radius: 30px; + font-size: 0.875rem; + font-weight: 600; + pointer-events: none; + opacity: 0; + transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); + z-index: 9999; + white-space: nowrap; + } + + #toast.show { + opacity: 1; + transform: translateX(-50%) translateY(0); + } + + #toast.success { background: var(--green); color: #fff; } + #toast.error { background: var(--pink); color: #fff; } + + /* ─── Divider ─── */ + .divider { + width: 1px; + height: 20px; + background: var(--border); + flex-shrink: 0; + } + + /* hidden util */ + .hidden { display: none !important; } + + @media (max-width: 580px) { + .host-grid { grid-template-columns: 1fr; } + .live-actions { flex-direction: column; align-items: stretch; } + .topbar { flex-direction: column; gap: 12px; align-items: flex-start; } + } + +/* Low-End Device & Accessibility Optimizations */ +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; + } +} + +.file-row { + content-visibility: auto; + contain-intrinsic-size: 0 46px; +} diff --git a/web/khira/app.js b/web/khira/app.js index b9ff27f..6f2f168 100644 --- a/web/khira/app.js +++ b/web/khira/app.js @@ -1,1918 +1,338 @@ -/* ═══════════════════════════════════════════════════════════════════════════ - KHIRA — Aurora Engineering Console - ───────────────────────────────────────────────────────────────────────── - App logic + interaction library (vanilla JS, no deps): - · Custom glowing cursor (glow dot + tracer dot) - · Sparkle particle canvas (ambient floating dots) - · 3D tilt cards (perspective transform on mouse move) - · Magnetic buttons (subtle pull toward cursor when nearby) - · Ripple on click (Material-style) - · Number ticker (spring-physics count up) - · Stagger entrance for lists (via CSS class) - · Auth tab glow (sliding indicator) - · Spring-physics drawer/modal open/close - · 8s silent polling, X-Khira-User header, mock fallback - · 100% backend-compatible API contract preserved - ═══════════════════════════════════════════════════════════════════════════ */ +/* Khira — Material 3 UI. Same /khira/api/* contract, X-Khira-User header, 8s polling. */ 'use strict'; +const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)]; +const esc=s=>s==null?'':String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); +const ms=n=>`${n}`; +const ls=k=>{try{return localStorage.getItem(k)}catch(e){return null}}; +const S={u:null,t:[],us:[],e:[],ts:{},es:{},n:[],sec:'tickets',scope:'assigned',st:'',pr:'',ty:'',view:'board',q:'',ef:'',tid:null}; +const APPS=['Creator Suite Web','FastAPI Backend','Creator Suite Web Unified Dashboard','Batch Inpaint Service','Nexus Gateway','Other App']; +const ISS=['API Failure / 500 / 400 Error','UI Layout / Rendering Bug','Schema Sync / Mismatch','Performance / Latency','Auth / Permission','Other']; +const CATS=['DevOps & Infrastructure','Database & Storage','Access & Permissions','Design & UX','Internal Workflow & Tooling','Hardware & IT Support','Security & Compliance','General Task']; +const ROLES=[['frontend','Frontend Dev'],['backend','Backend Dev'],['tester','QA / Tester'],['lead','Team Lead'],['engineer','Engineer'],['security','Security']]; +const EAPPS=['Unified Dashboard Client','Dashboard Client','FastAPI Backend','Batch Inpaint']; +const PRI=[['P0','P0 · Critical'],['P1','P1 · High'],['P2','P2 · Medium'],['P3','P3 · Low']]; +const SEV=[['CRITICAL','Critical'],['HIGH','High'],['MEDIUM','Medium'],['LOW','Low']]; +const STAT={open:'Open',progress:'In progress',hold:'On hold',completed:'Completed'}; +const COLS=[['open','var(--out)'],['progress','var(--pri)'],['hold','var(--on-warn-c)'],['completed','var(--on-ter-c)']]; +const EL={unresolved:'Unresolved',escalated:'Escalated',resolved:'Resolved'}; -/* ════════════════════════════════════════════════════════════════════ - STATE - ════════════════════════════════════════════════════════════════════ */ -let currentUser = null; -let allTickets = []; -let allUsers = []; -let allErrors = []; -let errorStats = {}; -let activeTicketId = null; -let currentSection = 'tickets'; -let currentErrView = 'table'; -let currentScope = 'assigned'; -let currentView = 'kanban'; -let currentEscalateErrorId = null; -let resolveTargetErrorId = null; -let completeTargetTicketId = null; -let holdTargetTicketId = null; -let pollingTimer = null; -let notificationsList = []; -let lastUnreadCount = 0; -let searchQuery = ''; -let filterType = ''; -let filterPriority = ''; -let filterRole = ''; -let filterStatus = ''; -let createTicketType = 'application'; -let errSearchQuery = ''; -let errFilterApp = ''; -let errFilterSeverity = ''; -let errFilterStatus = ''; -let linkComposerAttach = null; -let createFormLinks = []; -let createFormFiles = []; -let desktopAlertsEnabled = false; -let lastSyncTime = null; -let SILENT = false; -let USING_MOCK = false; -let cursorRAF = null; -let cursorX = 0, cursorY = 0; -let glowX = 0, glowY = 0; -let dotX = 0, dotY = 0; - -/* ════════════════════════════════════════════════════════════════════ - MOCK BACKEND (preserved identical API contract) - ════════════════════════════════════════════════════════════════════ */ -const MOCK_USERS = [ - { username: 'alice', name: 'Alice Walker', role: 'frontend', role_display: 'Frontend Dev', avatar: '👩‍💻' }, - { username: 'bob', name: 'Bob Chen', role: 'backend', role_display: 'Backend Dev', avatar: '👨‍💻' }, - { username: 'charlie', name: 'Charlie Diaz', role: 'tester', role_display: 'QA / Tester', avatar: '🕵️‍♂️' }, - { username: 'admin', name: 'Admin Cole', role: 'lead', role_display: 'Team Lead', avatar: '⚡' } -]; -const MOCK_PASSWORDS = { alice: 'alice123', bob: 'bob123', charlie: 'charlie123', admin: 'admin123' }; -let MOCK_TICKETS = []; -let MOCK_ERRORS = []; -let MOCK_NOTIFS = []; -let MOCK_TICKET_SEQ = 1; -let MOCK_ERROR_SEQ = 1; - -function seedMockTicketsIfEmpty() { - if (MOCK_TICKETS.length) return; - MOCK_TICKETS = [ - { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'application', title: 'Hair Color Changer 500 Error when mask_image is omitted', app: 'Creator Suite Web', version: 'v2.4.1', feature: 'Hair Color Changer', api_key: 'Stable_Diffusion_Hair_Color_Changer', issue_type: 'API Failure / 500 / 400 Error', priority: 'P0', description: 'When a user submits the hair color change request without a mask_image, the backend returns 500 instead of a 400 with a friendly validation message.', assistance: 'Endpoint Debugging · Schema Validation Fix', context: 'curl -X POST /apis/flxk/hair-color-change -H "Content-Type: application/json" -d \'{"prompt":"red hair"}\'\n# 500 Internal Server Error\n# ZeroDivisionError: division by zero: normalized alpha matte has zero total density', status: 'open', assignee: MOCK_USERS[1], reporter: MOCK_USERS[2], created_at: new Date(Date.now() - 86400000).toISOString(), updated_at: new Date(Date.now() - 3600000).toISOString(), remarks: [], links: [{ url: 'https://github.com/khira/creator-suite/issues/142' }], files: [] }, - { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'application', title: 'Face Swapper UI misaligned on Safari 17', app: 'Creator Suite Web Unified Dashboard', version: 'v2.4.0', feature: 'Face Swapper', api_key: 'Face_Swapper_UI', issue_type: 'UI Layout / Rendering Bug', priority: 'P2', description: 'The face swapper component renders off-center on Safari 17 due to a flex baseline issue.', assistance: 'UI Layout Fix', context: 'Safari 17.0 on macOS 14 — viewport 1440x900', status: 'progress', assignee: MOCK_USERS[0], reporter: MOCK_USERS[2], created_at: new Date(Date.now() - 172800000).toISOString(), updated_at: new Date(Date.now() - 7200000).toISOString(), remarks: [{ author: MOCK_USERS[0], body: 'Investigating — confirmed the bug. Appears related to flex baseline alignment.', created_at: new Date(Date.now() - 7200000).toISOString() }], links: [{ url: 'https://github.com/khira/creator-suite/pull/142' }], files: [] }, - { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'application', title: 'Batch Inpaint queue stalls when GPU memory fragmented', app: 'FastAPI Backend', version: 'v2.3.5', feature: 'Batch Inpaint', api_key: 'Batch_Inpaint_Queue', issue_type: 'Performance / Latency', priority: 'P1', description: 'After ~3 hours of continuous batching, the queue stops draining. Likely torch.cuda memory fragmentation.', assistance: 'GPU Memory Profiling', context: 'CUDAOutOfMemory: try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True', status: 'hold', assignee: MOCK_USERS[1], reporter: MOCK_USERS[3], created_at: new Date(Date.now() - 259200000).toISOString(), updated_at: new Date(Date.now() - 86400000).toISOString(), remarks: [{ author: null, system: true, body: 'Ticket placed on hold: Waiting on GPU cluster node provisioning', created_at: new Date(Date.now() - 86400000).toISOString() }], links: [], files: [], hold_reason: 'Waiting on GPU cluster node provisioning' }, - { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'general', title: 'Configure Redis cache cluster node for telemetry persistence', general_category: 'DevOps & Infrastructure', department: 'Core Infrastructure', app: 'General / Non-App', feature: 'DevOps & Infrastructure', priority: 'P1', description: 'Provision Redis v7.2 cluster node in Oregon region and connect to telemetry pipeline.', assistance: 'Cluster Configuration & IAM Security Group setup', context: 'AWS ElastiCache Redis Cluster · VPC subnet-08123\nRequires TLS in-transit encryption enabled.', status: 'open', assignee: MOCK_USERS[1], reporter: MOCK_USERS[3], created_at: new Date(Date.now() - 48000000).toISOString(), updated_at: new Date(Date.now() - 12000000).toISOString(), remarks: [], links: [{ url: 'https://aws.amazon.com/elasticache/' }], files: [] }, - { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'general', title: 'Provision S3 staging bucket write credentials for QA team', general_category: 'Access & Permissions', department: 'Security & Access', app: 'General / Non-App', feature: 'Access & Permissions', priority: 'P2', description: 'Generate IAM read/write policy for s3://cre-staging-artifacts for regression testing suite.', assistance: 'IAM Policy & Access Key Creation', context: 'Bucket: s3://cre-staging-artifacts/qa-test-runs/\nExpiration: 90 days', status: 'progress', assignee: MOCK_USERS[0], reporter: MOCK_USERS[2], created_at: new Date(Date.now() - 72000000).toISOString(), updated_at: new Date(Date.now() - 18000000).toISOString(), remarks: [], links: [], files: [] }, - { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'application', title: 'Auth token refresh race on tab focus', app: 'Creator Suite Web', version: 'v2.4.1', feature: 'Auth', api_key: 'Auth_Token_Refresh', issue_type: 'Auth / Permission', priority: 'P3', description: 'When two tabs are open and one refreshes the token, the other briefly shows "Unauthorized" until next sync.', assistance: 'Token Sync Fix', context: '', status: 'completed', assignee: MOCK_USERS[0], reporter: MOCK_USERS[3], created_at: new Date(Date.now() - 432000000).toISOString(), updated_at: new Date(Date.now() - 172800000).toISOString(), remarks: [{ author: MOCK_USERS[0], body: 'Added BroadcastChannel-based token sync. Verified across tabs.', created_at: new Date(Date.now() - 172800000).toISOString() }, { author: null, system: true, body: 'Ticket marked as completed: Fixed via BroadcastChannel sync, merged PR #142', created_at: new Date(Date.now() - 172800000).toISOString() }], links: [{ url: 'https://github.com/khira/creator-suite/pull/142' }], files: [], resolution: 'Fixed via BroadcastChannel sync, merged PR #142' } - ]; +/* ── API ── */ +async function api(p,m='GET',b){ + const h={},un=S.u?.username||ls('khira_active_user'); + if(un)h['X-Khira-User']=un; + if(m!=='GET')h['Content-Type']='application/json'; + try{ + const r=await fetch(p,{method:m,headers:h,body:b?JSON.stringify(b):undefined}); + const j=(r.headers.get('content-type')||'').includes('json')?await r.json():{}; + if(!r.ok){j._f=1;if(!j.error)j.error='Request failed ('+r.status+')'} + return j; + }catch(e){return{_f:1,error:'Network error'}} } -function seedMockErrorsIfEmpty() { - if (MOCK_ERRORS.length) return; - MOCK_ERRORS = [ - { id: `ERR-${String(MOCK_ERROR_SEQ++).padStart(3, '0')}`, app: 'FastAPI Backend', environment: 'Production', service: 'Hair Color Changer', endpoint: 'POST /apis/flxk/hair-color-change', exception_type: 'ZeroDivisionError', severity: 'HIGH', message: 'division by zero: normalized alpha matte has zero total density', stack_trace: 'Traceback (most recent call last):\n File "/app/api/hair_color.py", line 142, in hair_color_change\n alpha = normalize_alpha(mask_image)\n File "/app/utils/alpha.py", line 28, in normalize_alpha\n return alpha / alpha.sum()\nZeroDivisionError: division by zero: normalized alpha matte has zero total density', payload: '{"api_key": "Stable_Diffusion_Hair_Color_Changer", "model": "flux-fill", "prompt": "red hair", "mask_image": null}', status: 'unresolved', events: 7, first_seen: new Date(Date.now() - 86400000).toISOString(), last_seen: new Date(Date.now() - 3600000).toISOString(), reported_by: 'telemetry', escalated_ticket_id: null, resolution_notes: null }, - { id: `ERR-${String(MOCK_ERROR_SEQ++).padStart(3, '0')}`, app: 'Dashboard Client', environment: 'Production', service: 'Unified Dashboard', endpoint: 'GET /khira/api/stats', exception_type: 'TypeError', severity: 'MEDIUM', message: "Cannot read properties of undefined (reading 'length')", stack_trace: 'TypeError: Cannot read properties of undefined (reading \'length\')\n at renderKanban (app.js:318:42)\n at refreshData (app.js:201:9)', payload: '{"scope": "assigned"}', status: 'unresolved', events: 3, first_seen: new Date(Date.now() - 172800000).toISOString(), last_seen: new Date(Date.now() - 7200000).toISOString(), reported_by: 'telemetry', escalated_ticket_id: null, resolution_notes: null }, - { id: `ERR-${String(MOCK_ERROR_SEQ++).padStart(3, '0')}`, app: 'Batch Inpaint', environment: 'Production', service: 'Batch Inpaint Queue', endpoint: 'POST /apis/batch/inpaint', exception_type: 'CUDAOutOfMemory', severity: 'CRITICAL', message: 'CUDA out of memory. Tried to allocate 2.00 GiB. GPU 0 has a total capacity of 23.71 GiB of which 1.23 GiB is free.', stack_trace: 'torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 GiB.', payload: '{"batch_size": 16, "model": "flux-fill"}', status: 'resolved', events: 2, first_seen: new Date(Date.now() - 259200000).toISOString(), last_seen: new Date(Date.now() - 86400000).toISOString(), reported_by: 'telemetry', escalated_ticket_id: 'KHR-003', resolution_notes: 'Reduced default batch_size from 16 to 8' } - ]; +/* ── helpers ── */ +const pri=t=>{const p=(t.priority||'P3').toUpperCase();return{CRITICAL:'P0',HIGH:'P1',MEDIUM:'P2',LOW:'P3'}[p]||p}; +const st=t=>{const s=(t.status||'open').toLowerCase();return s==='in_progress'?'progress':s==='on_hold'?'hold':s}; +const ek=e=>e.status==='resolved'?'resolved':e.escalated_ticket_id?'escalated':'unresolved'; +const who=(u,alt)=>u?`${u.avatar||'👤'} ${u.name}`:(alt||'—'); +const usOpts=b=>[...(b?[['','Choose developer']]:[]),...S.us.map(u=>[u.username,`${u.name} · ${u.role_display}`])]; +function ago(iso){if(!iso)return'—';const d=new Date(iso);if(isNaN(d))return iso;const s=Math.floor((Date.now()-d)/1e3);if(s<60)return'just now';const m=Math.floor(s/60);if(m<60)return m+'m ago';const h=Math.floor(m/60);if(h<24)return h+'h ago';const x=Math.floor(h/24);return x<30?x+'d ago':d.toLocaleDateString()} +const greet=()=>{const h=new Date().getHours();return h<5?'Working late':h<12?'Good morning':h<17?'Good afternoon':h<21?'Good evening':'Working late'}; +const put=(sel,html)=>{const el=typeof sel==='string'?$(sel):sel;if(el._h!==html){el.innerHTML=html;el._h=html}return el}; +let tt;function toast(m,t){const s=$('#snack');s.textContent=m;s.style.background=t==='err'?'var(--err)':'';s.classList.add('on');clearTimeout(tt);tt=setTimeout(()=>s.classList.remove('on'),3500)} +const busy=async(b,fn)=>{b.disabled=true;try{return await fn()}finally{b.disabled=false}}; +const chk=f=>{f.querySelectorAll('.bad').forEach(x=>x.classList.remove('bad'));const bad=[...f.querySelectorAll('[required]:not(:disabled)')].filter(x=>!x.value.trim());bad.forEach(x=>x.closest('.fld').classList.add('bad'));if(bad.length){bad[0].focus();toast('Fill in the required fields','err')}return!bad.length}; + +/* ── form builders ── */ +function fld(n,l,o={}){ + const r=o.req?' required':'',t=o.t||'text';let c; + if(t==='select')c=``; + else if(t==='area')c=``; + else c=``; + return``; +} +const rad=(n,items,cur)=>`
${items.map(([v,l])=>``).join('')}
`; + +function dlg(o){ + const d=$('#dlg');d.className=o.wide?'wide':''; + d.innerHTML=`

${o.title}

${o.sub?`

${o.sub}

`:''}
${o.body}
${o.alt?``:''}
`; + const f=d.querySelector('form'); + if(o.alt)f.querySelector('[data-alt]').onclick=o.alt[1]; + if(o.init)o.init(f); + f.onsubmit=async e=>{ + e.preventDefault();if(!chk(f))return; + const v=Object.fromEntries([...new FormData(f)].map(([k,x])=>[k,typeof x==='string'?x.trim():x])); + await busy(f.querySelector('.fb'),async()=>{if(await o.go(v)!==false&&d.open)d.close()}); + }; + if(!d.open)d.showModal(); } -function mockResponse(path, options) { - const method = (options.method || 'GET').toUpperCase(); - const body = options.body && options.body.startsWith('{') ? JSON.parse(options.body) : {}; - const headers = options.headers || {}; - if (path === '/khira/api/auth/me') { - const u = headers['X-Khira-User'] && MOCK_USERS.find(x => x.username === headers['X-Khira-User']); - return u ? { authenticated: true, user: u } : { authenticated: false }; - } - if (path === '/khira/api/auth/login') { - const u = MOCK_USERS.find(x => x.username === body.username); - return (u && MOCK_PASSWORDS[body.username] === body.password) ? { user: u } : { error: 'Invalid credentials' }; - } - if (path === '/khira/api/auth/register') { - if (MOCK_USERS.find(x => x.username === body.username)) return { error: 'Username taken' }; - const roleDisplay = { frontend: 'Frontend Dev', backend: 'Backend Dev', tester: 'QA / Tester', lead: 'Team Lead', engineer: 'Engineer', security: 'Security' }[body.role] || body.role; - const u = { username: body.username, name: body.name, role: body.role, role_display: roleDisplay, avatar: '🚀' }; - MOCK_USERS.push(u); MOCK_PASSWORDS[body.username] = body.password; - return { user: u }; - } - if (path === '/khira/api/auth/logout') return { ok: true }; - if (path === '/khira/api/auth/profile') { - const u = MOCK_USERS.find(x => x.username === currentUser.username); - if (u) { - if (body.name) u.name = body.name; - if (body.role) { u.role = body.role; u.role_display = { frontend: 'Frontend Dev', backend: 'Backend Dev', tester: 'QA / Tester', lead: 'Team Lead', engineer: 'Engineer', security: 'Security' }[body.role] || body.role; } - if (body.avatar) u.avatar = body.avatar; - return { user: u }; - } - return { error: 'Not found' }; - } - if (path === '/khira/api/users') return { users: MOCK_USERS }; - if (path === '/khira/api/tickets' && method === 'GET') { seedMockTicketsIfEmpty(); return { tickets: MOCK_TICKETS }; } - if (path === '/khira/api/tickets' && method === 'POST') { - const id = `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`; - const reporter = currentUser ? { username: currentUser.username, name: currentUser.name, role_display: currentUser.role_display, avatar: currentUser.avatar } : null; - const assignee = MOCK_USERS.find(u => u.username === body.assignee_username); - const isGen = (body.ticket_type === 'general'); - const t = { - id, - ticket_type: isGen ? 'general' : 'application', - general_category: body.general_category || '', - department: body.department || '', - title: body.title, - app: body.app || (isGen ? 'General / Non-App' : '—'), - version: body.version || (isGen ? '—' : ''), - feature: body.feature || body.general_category || '', - api_key: body.api_key || '', - issue_type: body.issue_type || (isGen ? 'General Task' : ''), - priority: body.priority, - description: body.description, - assistance: body.assistance, - context: body.context || '', - status: 'open', - assignee, - reporter, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - remarks: [], - links: body.links || [], - files: [] - }; - MOCK_TICKETS.unshift(t); - return { ticket: t }; - } - if (path === '/khira/api/stats') { - seedMockTicketsIfEmpty(); - const u = headers['X-Khira-User']; - const mine = MOCK_TICKETS.filter(t => t.assignee && t.assignee.username === u); - const reported = MOCK_TICKETS.filter(t => t.reporter && t.reporter.username === u); - return { total: MOCK_TICKETS.length, my_assigned: mine.filter(t => t.status === 'open' || t.status === 'progress').length, my_created: reported.length, on_hold: MOCK_TICKETS.filter(t => t.status === 'hold').length, completed: MOCK_TICKETS.filter(t => t.status === 'completed').length, my_held: mine.filter(t => t.status === 'hold').length, my_completed: mine.filter(t => t.status === 'completed').length }; - } - const tm = path.match(/^\/khira\/api\/tickets\/([^/]+)\/(.+)$/); - if (tm) { - const [, tid, action] = tm; - const t = MOCK_TICKETS.find(x => x.id === tid); - if (!t) return { error: 'Not found' }; - if (action === 'links' && method === 'GET') return { links: t.links || [] }; - if (action === 'attachments' && method === 'GET') return { files: t.files || [] }; - if (action === 'remarks' && method === 'POST') { - const r = { author: currentUser ? { username: currentUser.username, name: currentUser.name, avatar: currentUser.avatar, role_display: currentUser.role_display } : null, body: body.body, links: body.links || [], created_at: new Date().toISOString() }; - t.remarks = t.remarks || []; t.remarks.unshift(r); t.updated_at = new Date().toISOString(); - return { remark: r }; - } - if (action === 'links' && method === 'POST') { t.links = t.links || []; t.links.push({ url: body.url, added_at: new Date().toISOString() }); return { link: { url: body.url } }; } - if (action === 'priority') { t.priority = body.priority; t.updated_at = new Date().toISOString(); return { ticket: t }; } - if (action === 'reassign') { t.assignee = MOCK_USERS.find(u => u.username === body.assignee_username) || t.assignee; t.updated_at = new Date().toISOString(); return { ticket: t }; } - if (action === 'hold') { - t.status = 'hold'; t.hold_reason = body.reason; - t.remarks = t.remarks || []; t.remarks.unshift({ author: null, system: true, body: `Ticket placed on hold: ${body.reason}`, created_at: new Date().toISOString() }); - t.updated_at = new Date().toISOString(); - return { ticket: t }; - } - if (action === 'complete') { - t.status = 'completed'; t.resolution = body.resolution; - t.remarks = t.remarks || []; t.remarks.unshift({ author: null, system: true, body: `Ticket marked as completed: ${body.resolution}`, created_at: new Date().toISOString() }); - t.updated_at = new Date().toISOString(); - return { ticket: t }; - } - if (action === 'resume') { - t.status = 'progress'; - t.remarks = t.remarks || []; t.remarks.unshift({ author: null, system: true, body: 'Ticket resumed from hold', created_at: new Date().toISOString() }); - t.updated_at = new Date().toISOString(); - return { ticket: t }; - } - } - if (path === '/khira/api/notifications') return { notifications: MOCK_NOTIFS }; - if (path === '/khira/api/notifications/read') { MOCK_NOTIFS.forEach(n => n.read = true); return { ok: true }; } - if (path === '/khira/api/errors' && method === 'GET') { seedMockErrorsIfEmpty(); return { errors: MOCK_ERRORS }; } - if (path === '/khira/api/errors' && method === 'POST') { - const id = `ERR-${String(MOCK_ERROR_SEQ++).padStart(3, '0')}`; - const e = { id, app: body.app, environment: body.environment, service: body.service, endpoint: body.endpoint || '', exception_type: body.exception_type, severity: body.severity, message: body.message, stack_trace: body.stack_trace || '', payload: body.payload || '', status: 'unresolved', events: 1, first_seen: new Date().toISOString(), last_seen: new Date().toISOString(), reported_by: currentUser ? currentUser.username : null, escalated_ticket_id: null, resolution_notes: null }; - MOCK_ERRORS.unshift(e); - return { error: e }; - } - if (path === '/khira/api/errors/stats') { - seedMockErrorsIfEmpty(); - return { total: MOCK_ERRORS.length, unresolved: MOCK_ERRORS.filter(e => e.status === 'unresolved').length, resolved: MOCK_ERRORS.filter(e => e.status === 'resolved').length, escalated: MOCK_ERRORS.filter(e => e.escalated_ticket_id).length }; - } - const em = path.match(/^\/khira\/api\/errors\/([^/]+)\/(.+)$/); - if (em) { - const [, eid, action] = em; - const e = MOCK_ERRORS.find(x => x.id === eid); - if (!e) return { error: 'Not found' }; - if (action === 'status') { e.status = body.status; e.resolution_notes = body.resolution_notes; e.resolved_at = new Date().toISOString(); return { error: e }; } - if (action === 'escalate') { - const id = `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`; - const assignee = MOCK_USERS.find(u => u.username === body.assignee_username); - const t = { id, title: body.title, app: e.app, version: '—', feature: e.service, api_key: e.endpoint, issue_type: 'API Failure / 500 / 400 Error', priority: body.priority, description: e.message, assistance: body.notes || 'Escalated from error telemetry', context: e.stack_trace || e.payload || '', status: 'open', assignee, reporter: { username: 'system', name: 'Khira Telemetry', role_display: 'System', avatar: '⚡' }, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), remarks: [], links: [], files: [], escalated_from_error: e.id }; - MOCK_TICKETS.unshift(t); - e.escalated_ticket_id = id; e.status = 'escalated'; - return { ticket: t }; - } - } - return { error: 'Mock endpoint not found: ' + path }; +/* ── auth ── */ +async function boot(){ + theme(document.documentElement.dataset.theme||'light'); + const r=await api('/khira/api/auth/me'); + if(r.authenticated&&r.user)enter(r.user);else $('#auth').hidden=false; +} +async function enter(u){ + S.u=u;try{localStorage.setItem('khira_active_user',u.username)}catch(e){} + $('#auth').hidden=true;$('#app').hidden=false; + $('#me').textContent=u.avatar||'👤';$('#hi').textContent=`${greet()}, ${(u.name||'').split(' ')[0]}`; + const r=await api('/khira/api/users');S.us=r.users||[]; + nav('tickets');await refresh(true); +} +async function logout(){ + await api('/khira/api/auth/logout','POST'); + try{localStorage.removeItem('khira_active_user')}catch(e){} + S.u=null;$('#dlg').close();$('#sheet').close();$('#app').hidden=true;$('#auth').hidden=false;toast('Signed out'); } -async function khiraFetch(path, options = {}) { - try { - const res = await fetch(path, options); - const ct = res.headers.get('content-type') || ''; - if (!res.ok || !ct.includes('application/json')) { - // Not a real API JSON response (might be HTML fallback from static server) - throw new Error('Not JSON API'); - } - USING_MOCK = false; - return await res.json(); - } catch (err) { - USING_MOCK = true; - return mockResponse(path, options); - } +/* ── data + render ── */ +async function refresh(anim){ + if(!S.u)return; + const[t,s,n,e,es]=await Promise.all(['tickets','stats','notifications','errors','errors/stats'].map(p=>api('/khira/api/'+p))); + S.t=t.tickets||S.t;S.ts=s._f?S.ts:s;S.e=e.errors||S.e;S.es=es._f?S.es:es;S.n=n.notifications||S.n; + $('#dot').hidden=!S.n.some(x=>!x.read); + render(anim); } -async function khiraSend(path, options) { - try { - const res = await fetch(path, options); - const ct = res.headers.get('content-type') || ''; - if (!res.ok || !ct.includes('application/json')) { - throw new Error('Not JSON API'); - } - USING_MOCK = false; - return await res.json(); - } catch (err) { - USING_MOCK = true; - return mockResponse(path, options); - } +const render=a=>S.sec==='tickets'?renderT(a):renderE(a); +const tile=(n,l,k)=>``; +const chipRow=(items,cur,attr)=>items.map(([k,l])=>``).join(''); + +function fT(){ + const me=S.u.username; + return S.t.filter(t=>{ + if(S.scope==='assigned'&&(t.assignee?.username||t.assigned_to)!==me)return false; + if(S.scope==='reported'&&(t.reporter?.username||t.created_by)!==me)return false; + if(S.ty&&(t.ticket_type||'application')!==S.ty)return false; + if(S.pr&&pri(t)!==S.pr)return false; + if(S.st&&st(t)!==S.st)return false; + return!S.q||[t.id,t.title,t.general_category,t.department,t.app,t.feature,t.api_key,t.assignee?.name].join(' ').toLowerCase().includes(S.q); + }); +} +const sub=t=>t.ticket_type==='general'?(t.general_category||t.department||'General'):(t.app||t.app_name||'—'); + +function renderT(anim){ + const s=S.ts,f=fT(); + put('#stats',tile(s.my_assigned,'Assigned to me','sa')+tile(s.my_created,'Filed by me','sr')+tile(s.on_hold,'On hold','sh')+tile(s.completed,'Completed','sc')); + put('#tabs',[['assigned','Assigned to me',s.my_assigned],['reported','Created by me',s.my_created],['all','All tickets',s.total]].map(([k,l,n])=>``).join('')); + put('#stChips',chipRow([['','All'],...Object.entries(STAT)],S.st,'data-st')); + $('#sum').textContent=`You have ${s.my_assigned||0} active tasks and ${s.my_held||0} on hold.`; + $('#fp').value=S.pr;$('#ft').value=S.ty; + $$('#vsw button').forEach(b=>b.classList.toggle('on',b.dataset.v===S.view)); + $('#board').hidden=S.view!=='board';$('#list').hidden=S.view!=='list'; + $('#board').classList.toggle('anim',!!anim);$('#list').classList.toggle('anim',!!anim); + if(S.view==='board'){ + put('#board',COLS.map(([k,c])=>{ + const rows=f.filter(t=>st(t)===k||(!STAT[st(t)]&&k==='open')); + return`

${STAT[k]}${rows.length}

${rows.map((t,i)=>{ + const p=pri(t),n=(t.remarks||[]).length; + return`
${esc(t.id)}${t.ticket_type==='general'?'General':'App'}${p}

${esc(t.title)}

${esc(sub(t))}${n?`${ms('chat_bubble').replace('class="ms"','class="ms" style="font-size:16px"')}${n}`:''}${esc(t.assignee?.avatar||'👤')}
`; + }).join('')||'
No tickets
'}
`; + }).join('')); + }else{ + put('#list',f.length?f.map((t,i)=>{ + const p=pri(t),s2=st(t); + return`
${p}

${esc(t.title)}

${esc(t.id)} · ${esc(sub(t))} · ${esc(t.assignee?.name||t.assigned_to_name||'Unassigned')}

${STAT[s2]||esc(s2)}${ago(t.updated_at)}
`; + }).join(''):`
${ms('confirmation_number')}

No tickets match these filters.

`); + } + put('#title',S.sec==='tickets'?'Tickets':'Errors'); } -/* ════════════════════════════════════════════════════════════════════ - INTERACTION LIBRARY — vanilla JS implementations - ════════════════════════════════════════════════════════════════════ */ - -/* ─── Custom cursor (glow + tracer dot) ───────────────────────────── */ -function initCustomCursor() { - const glow = document.getElementById('cursorGlow'); - const dot = document.getElementById('cursorDot'); - if (!glow || !dot) return; - if (window.matchMedia('(hover: none) and (pointer: coarse)').matches) return; - - document.addEventListener('mousemove', (e) => { - cursorX = e.clientX; - cursorY = e.clientY; - if (!cursorRAF) cursorRAF = requestAnimationFrame(animateCursor); - }); - - document.addEventListener('mouseover', (e) => { - if (e.target.closest('button, a, .kanban-card, .stat-tile, .err-card, [onclick], .persona-btn, .nav-item, input, select, textarea, label')) { - glow.classList.add('is-hover'); - } - }); - document.addEventListener('mouseout', (e) => { - if (e.target.closest('button, a, .kanban-card, .stat-tile, .err-card, [onclick], .persona-btn, .nav-item, input, select, textarea, label')) { - glow.classList.remove('is-hover'); - } - }); - - function animateCursor() { - // Glow lags slightly (spring follow) - glowX += (cursorX - glowX) * 0.18; - glowY += (cursorY - glowY) * 0.18; - // Dot follows tightly - dotX += (cursorX - dotX) * 0.45; - dotY += (cursorY - dotY) * 0.45; - glow.style.transform = `translate(${glowX}px, ${glowY}px) translate(-50%, -50%)`; - dot.style.transform = `translate(${dotX}px, ${dotY}px) translate(-50%, -50%)`; - if (Math.abs(cursorX - glowX) > 0.1 || Math.abs(cursorY - glowY) > 0.1 || Math.abs(cursorX - dotX) > 0.1 || Math.abs(cursorY - dotY) > 0.1) { - cursorRAF = requestAnimationFrame(animateCursor); - } else { - cursorRAF = null; - } - } - // Kick off animation loop - if (!cursorRAF) cursorRAF = requestAnimationFrame(animateCursor); +function renderE(anim){ + const s=S.es; + put('#estats',tile(s.total,'Total','et')+tile(s.unresolved,'Unresolved','eu')+tile(s.escalated,'Escalated','ee')+tile(s.resolved,'Resolved','er')); + put('#eChips',chipRow([['','All'],...Object.entries(EL)],S.ef,'data-ef')); + const f=S.e.filter(e=>(!S.ef||ek(e)===S.ef)&&(!S.q||[e.id,e.exception_type,e.message,e.endpoint,e.app].join(' ').toLowerCase().includes(S.q))); + $('#elist').classList.toggle('anim',!!anim); + put('#elist',f.length?f.map((e,i)=>{ + const sev=(e.severity||'MEDIUM').toUpperCase(),k=ek(e); + return`
${ms('error')}

${esc(e.exception_type)}

${esc(e.message)}

${esc(e.id)} · ${esc(e.app||'—')} · ${esc(e.endpoint||'—')}

${EL[k]}${e.events||1} events · ${ago(e.last_seen)}
`; + }).join(''):`
${ms('bug_report')}

No errors tracked.

`); } -/* ─── Sparkle canvas (ambient floating particles) ─────────────────── */ -function initSparkleCanvas() { - const canvas = document.getElementById('sparkleCanvas'); - if (!canvas) return; - const ctx = canvas.getContext('2d'); - let particles = []; - let raf; - - function resize() { - canvas.width = window.innerWidth; - canvas.height = window.innerHeight; - } - resize(); - window.addEventListener('resize', resize); - - function spawnParticle() { - return { - x: Math.random() * canvas.width, - y: Math.random() * canvas.height, - size: Math.random() * 1.8 + 0.5, - vx: (Math.random() - 0.5) * 0.18, - vy: -Math.random() * 0.25 - 0.05, - opacity: Math.random() * 0.6 + 0.2, - color: ['#10B981', '#06B6D4', '#8B5CF6', '#EC4899'][Math.floor(Math.random() * 4)] - }; - } - - for (let i = 0; i < 70; i++) particles.push(spawnParticle()); - - function tick() { - ctx.clearRect(0, 0, canvas.width, canvas.height); - particles.forEach((p, i) => { - p.x += p.vx; - p.y += p.vy; - if (p.y < -10) { - p.y = canvas.height + 10; - p.x = Math.random() * canvas.width; - } - if (p.x < -10) p.x = canvas.width + 10; - if (p.x > canvas.width + 10) p.x = -10; - ctx.beginPath(); - ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2); - ctx.fillStyle = p.color + Math.floor(p.opacity * 255).toString(16).padStart(2, '0'); - ctx.shadowColor = p.color; - ctx.shadowBlur = 8; - ctx.fill(); - }); - raf = requestAnimationFrame(tick); - } - tick(); +function nav(sec){ + S.sec=sec;S.q='';$('#q').value=''; + $$('.nav button').forEach(b=>b.classList.toggle('on',b.dataset.s===sec)); + $('#vT').hidden=sec!=='tickets';$('#vE').hidden=sec!=='errors'; + $('#q').placeholder=sec==='tickets'?'Search tickets':'Search errors'; + $('#fabl').textContent=sec==='tickets'?'New ticket':'Report error'; + render(true); } -/* ─── 3D Tilt cards ─────────────────────────────────────────────── */ -function initTilt() { - document.querySelectorAll('.tilt').forEach(el => { - let raf = null; - let rect = null; - el.addEventListener('mouseenter', () => { - rect = el.getBoundingClientRect(); - el.style.transition = 'transform 200ms ease-out'; - }); - el.addEventListener('mousemove', (e) => { - if (!rect) rect = el.getBoundingClientRect(); - const x = e.clientX - rect.left; - const y = e.clientY - rect.top; - const cx = rect.width / 2; - const cy = rect.height / 2; - const rx = ((y - cy) / cy) * -8; // max 8deg - const ry = ((x - cx) / cx) * 8; - if (raf) cancelAnimationFrame(raf); - raf = requestAnimationFrame(() => { - el.style.transform = `perspective(800px) rotateX(${rx}deg) rotateY(${ry}deg) translateY(-3px)`; - }); - }); - el.addEventListener('mouseleave', () => { - el.style.transition = 'transform 400ms cubic-bezier(0.34, 1.56, 0.64, 1)'; - el.style.transform = ''; - rect = null; - }); - }); +/* ── ticket sheet ── */ +function sheet(id){ + const t=S.t.find(x=>x.id===id);if(!t)return;S.tid=id; + const p=pri(t),s=st(t),g=t.ticket_type==='general',rem=t.remarks||[],links=(t.links||[]).map(l=>l.url||l); + const kv=(k,v,m)=>`
${k}
${esc(v||'—')}
`; + const meta=g?kv('Category',t.general_category)+kv('Department',t.department):kv('Application',t.app||t.app_name)+kv('Version',t.version)+kv('Feature',t.feature||t.feature_name)+kv('API key / route',t.api_key,1); + $('#sheet').innerHTML=`
${esc(t.id)}${p}${STAT[s]||esc(s)}
+

${esc(t.title)}

+
${fld('a','Assignee',{t:'select',opts:usOpts(),v:t.assignee?.username||t.assigned_to||'',d:'data-act="assign"'})}${fld('p','Priority',{t:'select',opts:PRI,v:p,d:'data-act="prio"'})}
+
${meta}${kv('Reported by',who(t.reporter,t.created_by_name))}
+
Assistance required

${esc(t.assistance||t.assistance_required||'—')}

+
Diagnostic context
${esc(t.context||t.additional_info||'No logs provided')}
+${links.length?`
Links
${links.map(u=>`${esc(String(u).replace(/^https?:\/\//,''))}`).join('')}
`:''} +
Activity · ${rem.length}
${rem.map(r=>{const sys=r.system||['created','hold','complete'].includes(r.type);return`
${sys?'Khira':esc(r.author?.name||r.author_name||'Anonymous')}${ago(r.created_at)}

${esc(r.text||r.body)}

`}).join('')} +
+
${s==='hold'?``:''}${s==='completed'?'':(s==='hold'?'':``)+``}
`; + if(!$('#sheet').open)$('#sheet').showModal(); +} +async function act(a,b,m){ + const r=await api(`/khira/api/tickets/${encodeURIComponent(S.tid)}/${a}`,'POST',b); + if(r._f){toast(r.error,'err');return false} + toast(m);await refresh();sheet(S.tid); +} +async function remark(){ + const ta=$('#rt'),b=ta.value.trim(); + if(!b){toast('Write a remark first','err');return} + const r=await api(`/khira/api/tickets/${encodeURIComponent(S.tid)}/remarks`,'POST',{body:b,links:[]}); + if(r._f){toast(r.error,'err');return} + toast('Remark posted');await refresh();sheet(S.tid); +} +const holdD=()=>dlg({title:'Put ticket on hold',sub:'Say what is blocking this ticket.',body:fld('reason','Reason',{t:'area',rows:4,req:1}),ok:'Hold ticket',go:v=>act('hold',{reason:v.reason},'Ticket on hold')}); +const doneD=()=>dlg({title:'Complete ticket',sub:'Describe how it was resolved.',body:fld('resolution','Resolution',{t:'area',rows:4,req:1}),ok:'Complete ticket',go:v=>act('complete',{resolution:v.resolution},'Ticket completed')}); + +/* ── create ticket ── */ +function newTicket(){ + dlg({wide:1,title:'New ticket',sub:`Reporting as ${esc(S.u.name)}`,ok:'Create ticket', + body:`${rad('type',[['application','Application'],['general','General']],'application')} +${fld('assignee_username','Assignee',{t:'select',opts:usOpts(1),req:1})}${fld('title','Title',{req:1})} +
${fld('app','Application',{t:'select',opts:[['','Select'],...APPS],req:1})}
${fld('version','Version',{req:1})}${fld('feature','Feature',{req:1})}
${fld('api_key','API key / route')}${fld('issue_type','Issue type',{t:'select',opts:[['','Select'],...ISS],req:1})}
+ +

Priority

${rad('priority',PRI,'P1')}
+${fld('description','Description',{t:'area',rows:4,req:1})}${fld('assistance','Assistance required',{req:1})}${fld('context','Context (cURL, logs, stack trace)',{t:'area',rows:4,mono:1})}${fld('link','Reference link',{t:'url'})}`, + init:f=>{const sw=()=>{const g=f.querySelector('[name=type]:checked').value;f.querySelectorAll('.grp').forEach(x=>{const on=x.dataset.g===g;x.hidden=!on;x.disabled=!on})};f.querySelectorAll('[name=type]').forEach(r=>r.onchange=sw);sw()}, + go:async v=>{ + const g=v.type==='general'; + const b=g?{ticket_type:'general',general_category:v.general_category,department:v.department,assignee_username:v.assignee_username,title:v.title,app:'General / Non-App',feature:v.general_category,priority:v.priority,description:v.description,assistance:v.assistance,context:v.context,links:v.link?[v.link]:[],files:[]} + :{ticket_type:'application',assignee_username:v.assignee_username,title:v.title,app:v.app,version:v.version,feature:v.feature,api_key:v.api_key,issue_type:v.issue_type,priority:v.priority,description:v.description,assistance:v.assistance,context:v.context,links:v.link?[{url:v.link}]:[]}; + const r=await api('/khira/api/tickets','POST',b); + if(!r.ticket){toast(r.error||'Could not create ticket','err');return false} + toast(`${r.ticket.id} created`);await refresh();nav('tickets');sheet(r.ticket.id); + }}); } -/* ─── Magnetic buttons (subtle pull toward cursor) ─────────────────── */ -function initMagnetic() { - if (window.matchMedia('(hover: none) and (pointer: coarse)').matches) return; - document.querySelectorAll('.magnetic').forEach(el => { - let raf = null; - el.addEventListener('mousemove', (e) => { - const rect = el.getBoundingClientRect(); - const x = e.clientX - (rect.left + rect.width / 2); - const y = e.clientY - (rect.top + rect.height / 2); - if (raf) cancelAnimationFrame(raf); - raf = requestAnimationFrame(() => { - el.style.transition = 'transform 200ms cubic-bezier(0.34, 1.56, 0.64, 1)'; - el.style.transform = `translate(${x * 0.18}px, ${y * 0.18}px)`; - }); - }); - el.addEventListener('mouseleave', () => { - el.style.transition = 'transform 400ms cubic-bezier(0.34, 1.56, 0.64, 1)'; - el.style.transform = ''; - }); - }); +/* ── errors ── */ +function errD(id){ + const e=S.e.find(x=>x.id===id);if(!e)return;const k=ek(e); + const blk=(l,v)=>v?`

${l}

${esc(v)}
`:''; + dlg({wide:1,title:esc(e.exception_type),sub:esc(`${e.id} · ${e.app||''}${e.environment?' · '+e.environment:''}`), + body:`
${esc(e.severity)}${EL[k]}${e.events||1} events · ${ago(e.last_seen)}

${esc(e.message)}

${blk('Endpoint',e.endpoint)}${blk('Stack trace',e.stack_trace)}${blk('Payload',e.payload)}${e.escalated_ticket_id?`

Escalated as ${esc(e.escalated_ticket_id)}

`:''}${e.resolution_notes?`

Resolution: ${esc(e.resolution_notes)}

`:''}`, + ok:k==='resolved'?'Close':'Escalate to ticket',alt:k==='unresolved'?['Resolve',()=>resolveD(id)]:null, + go:()=>{if(k!=='resolved'){escD(id);return false}}}); +} +function escD(id){ + const e=S.e.find(x=>x.id===id); + dlg({wide:1,title:'Escalate to ticket',sub:esc(`${e.id} · ${e.exception_type}`),ok:'Escalate', + body:fld('title','Ticket title',{req:1,v:`${e.exception_type}: ${(e.message||'').slice(0,60)}`})+fld('assignee_username','Assignee',{t:'select',opts:usOpts(1),req:1})+`

Priority

${rad('priority',PRI,'P0')}
`+fld('notes','Notes for the assignee',{t:'area'}), + go:async v=>{ + const r=await api(`/khira/api/errors/${encodeURIComponent(id)}/escalate`,'POST',{title:v.title,assignee_username:v.assignee_username,priority:v.priority,notes:v.notes}); + if(!r.ticket){toast(r.error||'Could not escalate','err');return false} + toast(`Escalated to ${r.ticket.id}`);await refresh();nav('tickets');sheet(r.ticket.id); + }}); +} +function resolveD(id){ + dlg({title:'Resolve error',sub:'Note the root cause and fix.',body:fld('resolution_notes','Resolution notes',{t:'area',rows:4,req:1}),ok:'Mark resolved', + go:async v=>{ + const r=await api(`/khira/api/errors/${encodeURIComponent(id)}/status`,'POST',{status:'resolved',resolution_notes:v.resolution_notes}); + if(r._f){toast(r.error,'err');return false} + toast('Error resolved');await refresh(); + }}); +} +function reportErr(){ + dlg({wide:1,title:'Report error',sub:'Log a runtime error for triage.',ok:'Report error', + body:`
${fld('app','Application',{t:'select',opts:[['','Select'],...EAPPS],req:1})}${fld('environment','Environment',{t:'select',opts:['Production','Staging','Development']})}
+${fld('service','Service',{req:1})}${fld('endpoint','Endpoint')}${fld('exception_type','Exception type',{req:1})} +

Severity

${rad('severity',SEV,'HIGH')}
+${fld('message','Message',{req:1})}${fld('stack_trace','Stack trace',{t:'area',rows:5,mono:1})}${fld('payload','Request payload',{t:'area',rows:3,mono:1})}`, + go:async v=>{ + const r=await api('/khira/api/errors','POST',v); + if(r._f||typeof r.error==='string'){toast(r.error||'Could not report error','err');return false} + toast(`${r.error?.id||'Error'} reported`);await refresh();nav('errors'); + }}); } -/* ─── Ripple on click ────────────────────────────────────────────── */ -function initRipple() { - document.addEventListener('click', (e) => { - const target = e.target.closest('.btn-aurora, .btn-ghost, .persona-btn, .nav-item, .scope-tab, .view-switch-btn'); - if (!target) return; - const rect = target.getBoundingClientRect(); - const size = Math.max(rect.width, rect.height); - const ripple = document.createElement('span'); - ripple.className = 'ripple'; - ripple.style.width = ripple.style.height = size + 'px'; - ripple.style.left = (e.clientX - rect.left - size / 2) + 'px'; - ripple.style.top = (e.clientY - rect.top - size / 2) + 'px'; - // Ensure parent is positioned - if (getComputedStyle(target).position === 'static') target.style.position = 'relative'; - target.style.overflow = 'hidden'; - target.appendChild(ripple); - setTimeout(() => ripple.remove(), 600); - }); +/* ── profile / notifications / theme ── */ +function profile(){ + dlg({title:'Profile',sub:`@${esc(S.u.username)}`,ok:'Save',alt:['Sign out',logout], + body:fld('name','Name',{req:1,v:S.u.name})+fld('role','Role',{t:'select',opts:ROLES,v:S.u.role})+fld('password','New password',{t:'password'}), + go:async v=>{ + const r=await api('/khira/api/auth/profile','POST',{name:v.name,role:v.role,avatar:S.u.avatar,password:v.password||undefined}); + if(!r.user){toast(r.error||'Could not update profile','err');return false} + S.u=r.user;$('#me').textContent=S.u.avatar||'👤';toast('Profile updated'); + const u=await api('/khira/api/users');S.us=u.users||S.us; + }}); +} +function pop(){ + const p=$('#pop');p.hidden=!p.hidden;if(p.hidden)return; + p.innerHTML=`
Notifications
`+(S.n.length?S.n.slice(0,12).map(n=>``).join(''):'
No notifications yet
'); +} +function theme(t){ + document.documentElement.dataset.theme=t;try{localStorage.setItem('khira_theme',t)}catch(e){} + $('#theme').innerHTML=ms(t==='dark'?'light_mode':'dark_mode');$('#tc').content=t==='dark'?'#0F1511':'#F5FBF5'; } -/* ─── Number ticker (spring physics count up) ───────────────────── */ -function tickNumber(el, target) { - if (!el) return; - if (SILENT) { el.textContent = target; return; } - const start = parseInt(String(el.textContent).replace(/[^\d-]/g, ''), 10) || 0; - if (start === target) { el.textContent = target; return; } - const t0 = performance.now(); - const dur = 700; - function step(t) { - const p = Math.min(1, (t - t0) / dur); - // Spring out: cubic ease-out with slight overshoot - const eased = 1 - Math.pow(1 - p, 4); - const val = Math.round(start + (target - start) * eased); - el.textContent = val; - if (p < 1) requestAnimationFrame(step); - else el.textContent = target; - } - requestAnimationFrame(step); -} - -/* ─── Theme ──────────────────────────────────────────────────────── */ -function applyTheme(theme) { - document.documentElement.setAttribute('data-theme', theme); - try { localStorage.setItem('khira_theme', theme); } catch (e) {} - const meta = document.getElementById('metaThemeColor'); - if (meta) meta.setAttribute('content', theme === 'light' ? '#F8FAFC' : '#050816'); - const icon = document.getElementById('themeIcon'); - const label = document.getElementById('themeLabel'); - if (icon) icon.className = theme === 'light' ? 'fa-solid fa-moon' : 'fa-solid fa-sun'; - if (label) label.textContent = theme === 'light' ? 'Dark' : 'Light'; -} -function toggleTheme() { - const next = document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light'; - applyTheme(next); -} - -/* ─── Sync status ────────────────────────────────────────────────── */ -function markSynced() { - lastSyncTime = Date.now(); - updateSyncLabel(); -} -function updateSyncLabel() { - const dot = document.getElementById('syncDot'); - const text = document.getElementById('syncText'); - if (!text) return; - if (!lastSyncTime) { - text.textContent = 'Connecting…'; - if (dot) dot.className = 'sync-dot connecting'; - return; - } - if (dot) dot.className = 'sync-dot live'; - const sec = Math.floor((Date.now() - lastSyncTime) / 1000); - if (sec < 4) text.textContent = 'Live · synced just now'; - else if (sec < 60) text.textContent = `Live · ${sec}s ago`; - else text.textContent = `Live · ${Math.floor(sec / 60)}m ago`; -} - -/* ════════════════════════════════════════════════════════════════════ - BOOT - ════════════════════════════════════════════════════════════════════ */ -document.addEventListener('DOMContentLoaded', async () => { - let theme = 'dark'; - try { theme = localStorage.getItem('khira_theme') || 'dark'; } catch (e) {} - applyTheme(theme); - - setInterval(updateSyncLabel, 5000); - - document.addEventListener('keydown', (e) => { - if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') { - e.preventDefault(); - focusSearch(); - } - if (e.key === 'Escape') closeEverything(); - }); - - const remarkTa = document.getElementById('remarkText'); - if (remarkTa) { - remarkTa.addEventListener('keydown', (e) => { - if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { - e.preventDefault(); - submitRemark(); - } - }); - } - - document.addEventListener('click', (e) => { - const dd = document.getElementById('notifDropdown'); - const btn = document.querySelector('.notif-btn'); - if (dd && dd.classList.contains('active') && !dd.contains(e.target) && !btn.contains(e.target)) { - dd.classList.remove('active'); - } - }); - - /* Init interaction library */ - initCustomCursor(); - initSparkleCanvas(); - initTilt(); - initMagnetic(); - initRipple(); - - await checkAuthStatus(); - await loadTeamUsers(); - await refreshData(); - initAlertsToggle(); - - pollingTimer = setInterval(async () => { - if (currentUser) await refreshData(true); - }, 8000); +/* ── events ── */ +const K={sa:()=>{S.scope='assigned';S.st=''},sr:()=>{S.scope='reported';S.st=''},sh:()=>{S.scope='all';S.st='hold'},sc:()=>{S.scope='all';S.st='completed'},et:()=>{S.ef=''},eu:()=>{S.ef='unresolved'},ee:()=>{S.ef='escalated'},er:()=>{S.ef='resolved'}}; +document.addEventListener('click',async e=>{ + const T=e.target,c=s=>T.closest(s);let x; + if(T.id==='sheet'||T.id==='dlg'){T.close();return} + if(x=c('[data-x]')){x.closest('dialog').close();return} + if(!c('#pop')&&!c('#bell'))$('#pop').hidden=true; + if(x=c('[data-s]'))return nav(x.dataset.s); + if(x=c('[data-k]')){K[x.dataset.k]();return render(true)} + if(x=c('[data-sc]')){S.scope=x.dataset.sc;return render(true)} + if(x=c('[data-st]')){S.st=x.dataset.st;return render(true)} + if(x=c('[data-ef]')){S.ef=x.dataset.ef;return render(true)} + if(x=c('[data-v]')){S.view=x.dataset.v;return render(true)} + if(x=c('[data-t]'))return sheet(x.dataset.t); + if(x=c('[data-e]'))return errD(x.dataset.e); + if(x=c('#atabs [data-a]')){const up=x.dataset.a==='up';$$('#atabs button').forEach(b=>b.classList.toggle('on',b===x));$('#fIn').hidden=up;$('#fUp').hidden=!up;return} + if(x=c('[data-d]')){$('#lu').value=x.dataset.d;$('#lp').value=x.dataset.d+'123';return $('#fIn').requestSubmit()} + if(x=c('[data-do]')){ + const d=x.dataset.do; + if(d==='hold')return holdD();if(d==='done')return doneD(); + if(d==='resume')return act('resume',undefined,'Ticket resumed'); + if(d==='readall'){await api('/khira/api/notifications/read','POST');await refresh();toast('All marked read');$('#pop').hidden=true} + return; + } + if(x=c('[data-n]')){$('#pop').hidden=true;if(x.dataset.n)sheet(x.dataset.n);return} + if(c('[data-copy]'))return navigator.clipboard.writeText($('#ctx').textContent).then(()=>toast('Copied')); + if(c('#fab'))return S.sec==='tickets'?newTicket():reportErr(); + if(c('#bell'))return pop(); + if(c('#me'))return profile(); + if(c('#theme'))return theme(document.documentElement.dataset.theme==='dark'?'light':'dark'); }); - -/* ════════════════════════════════════════════════════════════════════ - AUTH - ════════════════════════════════════════════════════════════════════ */ -async function checkAuthStatus() { - try { - const headers = {}; - const stored = localStorage.getItem('khira_active_user'); - if (stored) headers['X-Khira-User'] = stored; - const data = await khiraFetch('/khira/api/auth/me', { headers }); - if (data.authenticated && data.user) { - currentUser = data.user; - localStorage.setItem('khira_active_user', currentUser.username); - updateUserUI(); - showApp(); - } else { - currentUser = null; - showAuth(); - } - } catch (err) { showAuth(); } -} -function showApp() { - document.getElementById('authScreen').hidden = true; - document.getElementById('appShell').hidden = false; - initTilt(); - initMagnetic(); -} -function showAuth() { - document.getElementById('authScreen').hidden = false; - document.getElementById('appShell').hidden = true; -} - -function updateUserUI() { - if (!currentUser) return; - document.getElementById('chipAvatar').textContent = currentUser.avatar || '👤'; - document.getElementById('chipName').textContent = currentUser.name; - document.getElementById('chipRole').textContent = currentUser.role_display; - document.getElementById('welcomeAvatar').textContent = currentUser.avatar || '👤'; - document.getElementById('welcomeTitle').textContent = `${getGreeting()}, ${currentUser.name}`; - document.getElementById('welcomeRole').innerHTML = ` ${currentUser.role_display}`; - document.getElementById('createFormReporterName').textContent = currentUser.name; - document.getElementById('createFormReporterRole').textContent = currentUser.role_display; -} -function getGreeting() { - const h = new Date().getHours(); - if (h < 5) return 'Burning the midnight oil'; - if (h < 12) return 'Good morning'; - if (h < 17) return 'Good afternoon'; - if (h < 21) return 'Good evening'; - return 'Working late'; -} - -function switchAuthTab(tab) { - const loginTab = document.getElementById('authTabLogin'); - const regTab = document.getElementById('authTabRegister'); - const loginForm = document.getElementById('authLoginForm'); - const regForm = document.getElementById('authRegisterForm'); - const glow = document.getElementById('authTabGlow'); - if (tab === 'login') { - loginTab.classList.add('active'); regTab.classList.remove('active'); - loginForm.style.display = 'flex'; regForm.style.display = 'none'; - if (glow) glow.classList.remove('right'); - } else { - regTab.classList.add('active'); loginTab.classList.remove('active'); - regForm.style.display = 'flex'; loginForm.style.display = 'none'; - if (glow) glow.classList.add('right'); - } -} - -async function handleLoginSubmit(e) { - e.preventDefault(); - const btn = document.getElementById('loginSubmitBtn'); - const u = document.getElementById('loginUsername').value.trim(); - const p = document.getElementById('loginPassword').value; - if (!u || !p) return; - setLoading(btn, true); - try { - const data = await khiraSend('/khira/api/auth/login', { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ username: u, password: p }) - }); - if (data.user) { - currentUser = data.user; - localStorage.setItem('khira_active_user', currentUser.username); - updateUserUI(); - showApp(); - showToast(`Signed in as ${currentUser.name}`, 'success'); - await loadTeamUsers(); - await refreshData(); - } else { - showToast(data.error || 'Invalid credentials', 'error'); - } - } catch (err) { - showToast('Failed to sign in', 'error'); - } finally { - setLoading(btn, false); - } -} - -async function handleRegisterSubmit(e) { - e.preventDefault(); - const name = document.getElementById('regName').value.trim(); - const username = document.getElementById('regUsername').value.trim(); - const role = document.getElementById('regRole').value; - const password = document.getElementById('regPassword').value; - if (!name || !username || !password) return; - try { - const data = await khiraSend('/khira/api/auth/register', { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name, username, role, password }) - }); - if (data.user) { - currentUser = data.user; - localStorage.setItem('khira_active_user', currentUser.username); - updateUserUI(); - showApp(); - showToast(`Welcome, ${currentUser.name}`, 'success'); - await loadTeamUsers(); - await refreshData(); - } else { - showToast(data.error || 'Registration failed', 'error'); - } - } catch (err) { - showToast('Registration error', 'error'); - } -} - -async function quickLoginAs(persona) { - document.getElementById('loginUsername').value = persona; - document.getElementById('loginPassword').value = (MOCK_PASSWORDS[persona] || persona + '123'); - await handleLoginSubmit(new Event('submit')); -} - -async function handleLogout() { - try { await khiraSend('/khira/api/auth/logout', { method: 'POST' }); } catch (e) {} - localStorage.removeItem('khira_active_user'); - currentUser = null; - closeProfileModal(); - showAuth(); - showToast('Signed out', 'info'); -} - -/* ════════════════════════════════════════════════════════════════════ - TEAM USERS - ════════════════════════════════════════════════════════════════════ */ -async function loadTeamUsers() { - try { - const data = await khiraFetch('/khira/api/users'); - allUsers = data.users || []; - populateAssignees(); - } catch (err) { console.error('Failed loading users:', err); } -} -function populateAssignees() { - const opts = allUsers.map(u => ``).join(''); - const c = document.getElementById('createAssignee'); - const d = document.getElementById('drawerAssigneeSelect'); - const e = document.getElementById('escalateAssignee'); - if (c) c.innerHTML = '' + opts; - if (d) d.innerHTML = '' + opts; - if (e) e.innerHTML = '' + opts; -} - -/* ════════════════════════════════════════════════════════════════════ - DATA REFRESH & STATS - ════════════════════════════════════════════════════════════════════ */ -async function refreshData(silent = false) { - if (!currentUser) return; - SILENT = !!silent; - try { - const headers = { 'X-Khira-User': currentUser.username }; - const data = await khiraFetch('/khira/api/tickets', { headers }); - allTickets = data.tickets || []; - const stats = await khiraFetch('/khira/api/stats', { headers }); - updateStatsUI(stats); - await refreshNotifications(); - await loadErrors(true); - if (currentSection === 'tickets') renderCurrentView(); - else renderErrors(); - markSynced(); - } catch (err) { - if (!silent) console.error('Refresh failed:', err); - } finally { SILENT = false; } -} - -function updateStatsUI(s) { - tickNumber(document.getElementById('statAssigned'), s.my_assigned || 0); - tickNumber(document.getElementById('statCreated'), s.my_created || 0); - tickNumber(document.getElementById('statHold'), s.on_hold || 0); - tickNumber(document.getElementById('statCompleted'), s.completed || 0); - setText('scopeAssigned', s.my_assigned || 0); - setText('scopeReported', s.my_created || 0); - setText('scopeAll', s.total || 0); - setText('navCountTickets', s.total || allTickets.length || 0); - tickNumber(document.getElementById('wlActive'), s.my_assigned || 0); - tickNumber(document.getElementById('wlHold'), s.my_held || 0); - tickNumber(document.getElementById('wlDone'), s.my_completed || 0); - tickNumber(document.getElementById('wlTotal'), s.total || 0); - tickNumber(document.getElementById('profStatAssigned'), s.my_assigned || 0); - tickNumber(document.getElementById('profStatHeld'), s.my_held || 0); - tickNumber(document.getElementById('profStatDone'), s.my_completed || 0); - const sum = document.getElementById('welcomeSummary'); - if (sum) sum.textContent = `You have ${s.my_assigned || 0} active assigned tasks and ${s.my_held || 0} tickets on hold.`; -} -function setText(id, val) { - const el = document.getElementById(id); - if (el) el.textContent = val; -} - -/* ════════════════════════════════════════════════════════════════════ - SECTION / SCOPE / FILTERS - ════════════════════════════════════════════════════════════════════ */ -function switchSection(section) { - currentSection = section; - document.getElementById('navTickets').classList.toggle('active', section === 'tickets'); - document.getElementById('navErrors').classList.toggle('active', section === 'errors'); - document.getElementById('viewTickets').hidden = section !== 'tickets'; - document.getElementById('viewErrors').hidden = section !== 'errors'; - document.getElementById('ctaTickets').style.display = section === 'tickets' ? 'inline-flex' : 'none'; - document.getElementById('ctaErrors').style.display = section === 'errors' ? 'inline-flex' : 'none'; - if (section === 'tickets') { - document.getElementById('crumbTitle').textContent = 'Tickets & Tasks'; - document.getElementById('crumbSub').textContent = 'Engineering backlog'; - renderCurrentView(); - } else { - document.getElementById('crumbTitle').textContent = 'Error Tracking'; - document.getElementById('crumbSub').textContent = 'Runtime telemetry'; - renderErrors(); - } - closeMobileSidebar(); -} -function openMobileSidebar() { - document.getElementById('sidebar').classList.add('open'); - document.getElementById('sidebarBackdrop').classList.add('active'); -} -function closeMobileSidebar() { - const sb = document.getElementById('sidebar'); - const bd = document.getElementById('sidebarBackdrop'); - if (sb) sb.classList.remove('open'); - if (bd) bd.classList.remove('active'); -} -function filterBySidebarWorkload(key) { - if (currentSection !== 'tickets') { - switchSection('tickets'); - } - if (key === 'active') { - currentScope = 'assigned'; - filterStatus = ''; - const fs = document.getElementById('filterStatus'); - if (fs) fs.value = ''; - } else if (key === 'hold') { - currentScope = 'assigned'; - filterStatus = 'hold'; - const fs = document.getElementById('filterStatus'); - if (fs) fs.value = 'hold'; - } else if (key === 'completed') { - currentScope = 'assigned'; - filterStatus = 'completed'; - const fs = document.getElementById('filterStatus'); - if (fs) fs.value = 'completed'; - } else if (key === 'total') { - currentScope = 'all'; - filterStatus = ''; - filterType = ''; - filterPriority = ''; - filterRole = ''; - searchQuery = ''; - ['filterType', 'filterPriority', 'filterRole', 'filterStatus', 'searchInput'].forEach(id => { - const el = document.getElementById(id); - if (el) el.value = ''; - }); - } - document.querySelectorAll('.scope-tab').forEach(t => t.classList.toggle('active', t.dataset.scope === currentScope)); - updateSidebarActiveButtons(); - renderCurrentView(); -} - -function updateSidebarActiveButtons() { - const btns = ['wlBtnActive', 'wlBtnHold', 'wlBtnDone', 'wlBtnTotal']; - btns.forEach(id => { - const el = document.getElementById(id); - if (el) el.classList.remove('active'); - }); - if (currentScope === 'all' && !filterStatus && !filterPriority && !filterType && !filterRole && !searchQuery) { - const el = document.getElementById('wlBtnTotal'); - if (el) el.classList.add('active'); - } else if (currentScope === 'assigned') { - if (!filterStatus) { - const el = document.getElementById('wlBtnActive'); - if (el) el.classList.add('active'); - } else if (filterStatus === 'hold') { - const el = document.getElementById('wlBtnHold'); - if (el) el.classList.add('active'); - } else if (filterStatus === 'completed') { - const el = document.getElementById('wlBtnDone'); - if (el) el.classList.add('active'); - } - } -} - -function switchScope(scope) { - currentScope = scope; - document.querySelectorAll('.scope-tab').forEach(t => t.classList.toggle('active', t.dataset.scope === scope)); - updateSidebarActiveButtons(); - renderCurrentView(); -} -function onSearchInput(v) { searchQuery = v.toLowerCase(); renderCurrentView(); } -function onFilterChange(type, val) { - if (type === 'type') { - filterType = val; - const el = document.getElementById('filterType'); - if (el && el.value !== val) el.value = val; - } - if (type === 'priority') { - filterPriority = val; - const el = document.getElementById('filterPriority'); - if (el && el.value !== val) el.value = val; - } - if (type === 'role') { - filterRole = val; - const el = document.getElementById('filterRole'); - if (el && el.value !== val) el.value = val; - } - if (type === 'status') { - filterStatus = val; - const el = document.getElementById('filterStatus'); - if (el && el.value !== val) el.value = val; - } - updateSidebarActiveButtons(); - renderCurrentView(); -} -function focusSearch() { - const el = currentSection === 'tickets' ? document.getElementById('searchInput') : document.getElementById('errSearchInput'); - if (el) { el.focus(); el.select(); } -} -function getFilteredTickets() { - return allTickets.filter(t => { - if (currentScope === 'assigned' && (!t.assignee || t.assignee.username !== currentUser.username) && (t.assigned_to !== currentUser.username)) return false; - if (currentScope === 'reported' && (!t.reporter || t.reporter.username !== currentUser.username) && (t.created_by !== currentUser.username)) return false; - if (filterType && (t.ticket_type || 'application') !== filterType) return false; - - let pri = (t.priority || 'P3').toUpperCase(); - if (pri === 'CRITICAL') pri = 'P0'; - else if (pri === 'HIGH') pri = 'P1'; - else if (pri === 'MEDIUM') pri = 'P2'; - else if (pri === 'LOW') pri = 'P3'; - if (filterPriority && pri !== filterPriority.toUpperCase()) return false; - - const assigneeRole = t.assignee ? t.assignee.role : (t.assigned_to_role || ''); - if (filterRole && !assigneeRole.toLowerCase().includes(filterRole.toLowerCase())) return false; - - let s = (t.status || 'open').toLowerCase(); - if (s === 'in_progress') s = 'progress'; - if (s === 'on_hold') s = 'hold'; - if (filterStatus && s !== filterStatus.toLowerCase()) return false; - - if (searchQuery) { - const hay = `${t.id} ${t.title} ${t.ticket_type || ''} ${t.general_category || ''} ${t.department || ''} ${t.app || t.app_name || ''} ${t.feature || t.feature_name || ''} ${t.api_key || ''} ${t.assignee ? t.assignee.name : (t.assigned_to_name || '')}`.toLowerCase(); - if (!hay.includes(searchQuery)) return false; - } - return true; - }); -} -function switchView(view) { - currentView = view; - document.querySelectorAll('#viewTickets .view-switch-btn').forEach(b => b.classList.toggle('active', b.dataset.view === view)); - document.getElementById('kanbanView').hidden = view !== 'kanban'; - document.getElementById('tableView').hidden = view !== 'table'; - renderCurrentView(); -} -function renderCurrentView() { - if (currentView === 'kanban') renderKanban(); - else renderTable(); -} - -/* ════════════════════════════════════════════════════════════════════ - KANBAN RENDER - ════════════════════════════════════════════════════════════════════ */ -function renderKanban() { - const filtered = getFilteredTickets(); - const cols = { open: [], progress: [], hold: [], completed: [] }; - filtered.forEach(t => { - let s = (t.status || 'open').toLowerCase(); - if (s === 'in_progress') s = 'progress'; - if (s === 'on_hold') s = 'hold'; - if (cols[s]) cols[s].push(t); - else cols.open.push(t); - }); - [['open', 'colOpen', 'colOpenCount'], ['progress', 'colProgress', 'colProgCount'], ['hold', 'colHold', 'colHoldCount'], ['completed', 'colCompleted', 'colDoneCount']].forEach(([s, bodyId, countId], idx) => { - const body = document.getElementById(bodyId); - const count = document.getElementById(countId); - if (count) count.textContent = cols[s].length; - if (!body) return; - if (cols[s].length === 0) { - body.innerHTML = '
No tickets
'; - } else { - body.innerHTML = cols[s].map((t, i) => renderKanbanCard(t, i)).join(''); - body.querySelectorAll('.kanban-card').forEach((card, i) => { - card.style.animationDelay = (i * 40) + 'ms'; - card.addEventListener('click', () => openDrawer(card.dataset.id)); - }); - } - }); -} -function renderKanbanCard(t, idx) { - let pri = (t.priority || 'P3').toUpperCase(); - if (pri === 'CRITICAL') pri = 'P0'; - else if (pri === 'HIGH') pri = 'P1'; - else if (pri === 'MEDIUM') pri = 'P2'; - else if (pri === 'LOW') pri = 'P3'; - const priClass = pri.toLowerCase(); - const accentColor = { P0: '#EF4444', P1: '#F59E0B', P2: '#06B6D4', P3: '#64748B' }[pri] || '#64748B'; - - const isGen = (t.ticket_type === 'general'); - const typeTag = isGen - ? ` General` - : ` App`; - - const categoryOrApp = isGen - ? ` ${escapeHtml(t.general_category || t.department || 'General')}` - : ` ${escapeHtml(t.app || t.app_name || '—')}`; - - const assignee = t.assignee ? (t.assignee.avatar || '👤') : (t.assigned_to_role === 'Frontend Dev' ? '🎨' : t.assigned_to_role === 'Tester' ? '🕵️‍♂️' : '👨‍💻'); - const remarksCount = (t.remarks || []).length; - - return `
-
-
- ${escapeHtml(t.id)} - ${typeTag} -
- ${escapeHtml(pri)} -
-
${escapeHtml(t.title)}
-
- ${categoryOrApp} -
- ${remarksCount > 0 ? ` ${remarksCount}` : ''} - ${assignee} -
-
-
`; -} - -/* ════════════════════════════════════════════════════════════════════ - TABLE RENDER - ════════════════════════════════════════════════════════════════════ */ -function renderTable() { - const filtered = getFilteredTickets(); - const tbody = document.getElementById('ticketsTbody'); - const empty = document.getElementById('ticketsEmpty'); - if (!filtered.length) { tbody.innerHTML = ''; empty.hidden = false; return; } - empty.hidden = true; - tbody.innerHTML = filtered.map(t => { - const s = t.status || 'open'; - const sLabel = { open: 'Open', progress: 'In Progress', hold: 'On Hold', completed: 'Completed' }[s] || s; - let pri = (t.priority || 'P3').toUpperCase(); - if (pri === 'CRITICAL') pri = 'P0'; - else if (pri === 'HIGH') pri = 'P1'; - else if (pri === 'MEDIUM') pri = 'P2'; - else if (pri === 'LOW') pri = 'P3'; - - const isGen = (t.ticket_type === 'general'); - const typePill = isGen - ? ` General` - : ` App`; - const appCol = isGen - ? ` ${escapeHtml(t.general_category || t.department || 'General')}` - : ` ${escapeHtml(t.app || t.app_name || '—')}`; - - const assigneeName = t.assignee ? t.assignee.name : (t.assigned_to_name || t.assigned_to || '—'); - const assigneeAvatar = t.assignee ? (t.assignee.avatar || '👤') : '👤'; - const reporterName = t.reporter ? t.reporter.name : (t.created_by_name || t.created_by || '—'); - const reporterAvatar = t.reporter ? (t.reporter.avatar || '👤') : '👤'; - - return ` - ${escapeHtml(t.id)} - ${typePill} - ${escapeHtml(t.title)} - ${appCol} - ${escapeHtml(pri)} -
${assigneeAvatar}${escapeHtml(assigneeName)}
-
${reporterAvatar}${escapeHtml(reporterName)}
- ${sLabel} - ${formatTime(t.updated_at)} -
- `; - }).join(''); - tbody.querySelectorAll('tr').forEach(row => { - row.addEventListener('click', () => openDrawer(row.dataset.id)); - }); -} - -/* ════════════════════════════════════════════════════════════════════ - DRAWER - ════════════════════════════════════════════════════════════════════ */ -async function openDrawer(ticketId) { - activeTicketId = ticketId; - const t = allTickets.find(x => x.id === ticketId); - if (!t) return; - document.getElementById('drawerId').textContent = t.id; - let pri = (t.priority || 'P3').toUpperCase(); - if (pri === 'CRITICAL') pri = 'P0'; - else if (pri === 'HIGH') pri = 'P1'; - else if (pri === 'MEDIUM') pri = 'P2'; - else if (pri === 'LOW') pri = 'P3'; - const dp = document.getElementById('drawerPriority'); - dp.textContent = pri; - dp.className = 'priority-chip ' + pri; - const ds = document.getElementById('drawerStatus'); - let s = (t.status || 'open').toLowerCase(); - if (s === 'in_progress') s = 'progress'; - if (s === 'on_hold') s = 'hold'; - const sLabel = { open: 'Open', progress: 'In Progress', hold: 'On Hold', completed: 'Completed' }[s] || s; - if (ds) { - ds.textContent = sLabel; - ds.className = 'drawer-status ' + s; - } - document.getElementById('drawerTitle').textContent = t.title; - - const isGen = (t.ticket_type === 'general'); - const dtb = document.getElementById('drawerTypeBadge'); - if (dtb) { - dtb.textContent = isGen ? '⚙️ General' : '🚀 App'; - dtb.className = 'type-pill ' + (isGen ? 'type-pill-general' : 'type-pill-app'); - } - const appMeta = document.getElementById('drawerMetaApp'); - const genMeta = document.getElementById('drawerMetaGeneral'); - const assigneeStr = t.assignee ? `${t.assignee.avatar || '👤'} ${t.assignee.name}` : (t.assigned_to_name ? `👤 ${t.assigned_to_name}` : '—'); - const reporterStr = t.reporter ? `${t.reporter.avatar || '👤'} ${t.reporter.name}` : (t.created_by_name ? `👤 ${t.created_by_name}` : '—'); - - if (isGen) { - if (appMeta) appMeta.style.display = 'none'; - if (genMeta) genMeta.style.display = 'grid'; - setText('drawerGenCategory', t.general_category || 'General'); - setText('drawerGenDepartment', t.department || '—'); - setText('drawerGenTicketType', '⚙️ General Ticket'); - setText('drawerGenRefId', t.id); - setText('drawerGenAssignee', assigneeStr); - setText('drawerGenReporter', reporterStr); - } else { - if (appMeta) appMeta.style.display = 'grid'; - if (genMeta) genMeta.style.display = 'none'; - document.getElementById('drawerApp').textContent = t.app || t.app_name || '—'; - document.getElementById('drawerVersion').textContent = t.version || '—'; - document.getElementById('drawerFeature').textContent = t.feature || t.feature_name || '—'; - document.getElementById('drawerApiKey').textContent = t.api_key || '—'; - document.getElementById('drawerAssignee').textContent = assigneeStr; - document.getElementById('drawerReporter').textContent = reporterStr; - } - - document.getElementById('drawerAssistance').textContent = t.assistance || t.assistance_required || '—'; - document.getElementById('drawerContext').textContent = t.context || t.additional_info || 'No logs provided'; - const linksEl = document.getElementById('drawerLinks'); - let linksHtml = ''; - if (t.links && t.links.length) { - linksHtml = t.links.map((l, i) => { - const url = l.url || l; - return ``; - }).join(''); - } - linksEl.innerHTML = linksHtml; - const filesEl = document.getElementById('drawerFiles'); - const attachments = t.files || t.attachments || []; - if (attachments && attachments.length) { - filesEl.innerHTML = attachments.map((f, i) => `
${f.is_image || f.type === 'image' ? `` : ``}
${escapeHtml(f.name || 'file')}
${escapeHtml((f.size || 0) + ' B')}
`).join(''); - } else { - filesEl.innerHTML = ''; - } - const tl = document.getElementById('drawerTimeline'); - const remarks = t.remarks || []; - setText('drawerRemarksCount', remarks.length); - if (!remarks.length) { - tl.innerHTML = '
No remarks yet — be the first to post.
'; - } else { - tl.innerHTML = remarks.map(r => { - const rAuthor = r.author ? (r.author.avatar || '👤') + ' ' + escapeHtml(r.author.name) : (r.author_name ? '👤 ' + escapeHtml(r.author_name) : 'Anonymous'); - const rText = r.text || r.body || ''; - if (r.system || r.type === 'created' || r.type === 'hold' || r.type === 'complete') { - return `
Khira System${formatTime(r.created_at)}
${escapeHtml(rText)}
`; - } - return `
${rAuthor}${formatTime(r.created_at)}
${escapeHtml(rText)}${(r.links && r.links.length) ? r.links.map(l => ` ${escapeHtml((l.url || l).replace(/^https?:\/\//, '').slice(0, 30))}`).join('') : ''}
`; - }).join(''); - } - const da = document.getElementById('drawerAssigneeSelect'); - if (da) { - const uVal = t.assignee ? t.assignee.username : t.assigned_to; - if (uVal) da.value = uVal; - } - const dp2 = document.getElementById('drawerPrioritySelect'); - if (dp2) dp2.value = pri; - document.getElementById('btnHold').hidden = s === 'hold' || s === 'completed'; - document.getElementById('btnResume').hidden = s !== 'hold'; - document.getElementById('btnComplete').hidden = s === 'completed'; - document.getElementById('ticketDrawer').classList.add('active'); -} -function closeDrawer() { - document.getElementById('ticketDrawer').classList.remove('active'); - activeTicketId = null; -} -async function submitRemark() { - if (!activeTicketId) return; - const ta = document.getElementById('remarkText'); - const body = ta.value.trim(); - if (!body) { showToast('Remark body is empty', 'error'); return; } - const links = linkComposerAttach ? [linkComposerAttach] : []; - try { - await khiraSend(`/khira/api/tickets/${encodeURIComponent(activeTicketId)}/remarks`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ body, links }) - }); - ta.value = ''; - linkComposerAttach = null; - showToast('Remark posted', 'success'); - await refreshData(true); - openDrawer(activeTicketId); - } catch (err) { showToast('Failed to post remark', 'error'); } -} -async function reassignTicket(username) { - if (!activeTicketId || !username) return; - try { - await khiraSend(`/khira/api/tickets/${encodeURIComponent(activeTicketId)}/reassign`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ assignee_username: username }) - }); - showToast('Ticket reassigned', 'success'); - await refreshData(true); - openDrawer(activeTicketId); - } catch (err) { showToast('Failed to reassign', 'error'); } -} -async function changePriority(priority) { - if (!activeTicketId) return; - try { - await khiraSend(`/khira/api/tickets/${encodeURIComponent(activeTicketId)}/priority`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ priority }) - }); - showToast('Priority updated', 'success'); - await refreshData(true); - openDrawer(activeTicketId); - } catch (err) { showToast('Failed to update priority', 'error'); } -} -async function resumeTicket() { - if (!activeTicketId) return; - try { - await khiraSend(`/khira/api/tickets/${encodeURIComponent(activeTicketId)}/resume`, { - method: 'POST', headers: { 'Content-Type': 'application/json' } - }); - showToast('Ticket resumed', 'success'); - await refreshData(true); - openDrawer(activeTicketId); - } catch (err) { showToast('Failed to resume', 'error'); } -} -function copyText(what) { - let text = ''; - if (what === 'context') text = document.getElementById('drawerContext').textContent; - if (text) navigator.clipboard.writeText(text).then(() => showToast('Copied', 'info')); -} -async function removeDrawerLink(idx) { - if (!activeTicketId) return; - const t = allTickets.find(x => x.id === activeTicketId); - if (!t || !t.links) return; - t.links.splice(idx, 1); - openDrawer(activeTicketId); -} -async function removeDrawerFile(idx) { - if (!activeTicketId) return; - const t = allTickets.find(x => x.id === activeTicketId); - if (!t || !t.files) return; - t.files.splice(idx, 1); - openDrawer(activeTicketId); -} -async function onDrawerFileSelected(e) { - if (!activeTicketId) return; - const files = Array.from(e.target.files || []); - if (!files.length) return; - const t = allTickets.find(x => x.id === activeTicketId); - if (!t) return; - t.files = t.files || []; - for (const f of files) { - t.files.push({ name: f.name, size: f.size, is_image: f.type.startsWith('image/'), url: f.type.startsWith('image/') ? URL.createObjectURL(f) : null }); - } - openDrawer(activeTicketId); - showToast(`${files.length} file(s) attached`, 'success'); -} - -/* ════════════════════════════════════════════════════════════════════ - MODALS (Create / Hold / Complete / Report Error / Escalate / Resolve / Profile / Link) - ════════════════════════════════════════════════════════════════════ */ -function setCreateTicketType(type) { - createTicketType = type; - const btnApp = document.getElementById('tabTypeApp'); - const btnGen = document.getElementById('tabTypeGeneral'); - const appFields = document.getElementById('createAppFields'); - const genFields = document.getElementById('createGeneralFields'); - const modalHeading = document.getElementById('modalCreateHeading'); - const titleInput = document.getElementById('createTitle'); - const lblAssist = document.getElementById('lblCreateAssistance'); - const assistInput = document.getElementById('createAssistance'); - const lblContext = document.getElementById('lblCreateContext'); - const contextInput = document.getElementById('createContext'); - - if (btnApp) btnApp.classList.toggle('active', type === 'application'); - if (btnGen) btnGen.classList.toggle('active', type === 'general'); - - const secScopeTitle = document.getElementById('secScopeTitle'); - if (type === 'general') { - if (secScopeTitle) secScopeTitle.innerHTML = ' 2. Domain & Department Scope'; - if (appFields) appFields.style.display = 'none'; - if (genFields) genFields.style.display = 'block'; - if (modalHeading) modalHeading.textContent = 'New General Ticket'; - if (titleInput) titleInput.placeholder = 'e.g. Provision Redis cache cluster on AWS Oregon'; - if (lblAssist) lblAssist.innerHTML = 'Action Needed / Deliverable *'; - if (assistInput) assistInput.placeholder = 'e.g. S3 Bucket IAM Policy, SSL Certificate Renewal'; - if (lblContext) lblContext.textContent = 'Specifications / Instructions / Configuration Details'; - if (contextInput) contextInput.placeholder = 'Paste relevant IAM ARN, VPC subnet, environment configs, or technical requirements…'; - } else { - if (secScopeTitle) secScopeTitle.innerHTML = ' 2. Application Scope'; - if (appFields) appFields.style.display = 'block'; - if (genFields) genFields.style.display = 'none'; - if (modalHeading) modalHeading.textContent = 'New Application Ticket'; - if (titleInput) titleInput.placeholder = 'e.g. Hair Color Changer 500 Error when mask_image is omitted'; - if (lblAssist) lblAssist.innerHTML = 'Assistance Required *'; - if (assistInput) assistInput.placeholder = 'e.g. Endpoint Debugging, UI Layout Fix'; - if (lblContext) lblContext.textContent = 'Additional context (cURL, logs, payloads, stack trace)'; - if (contextInput) contextInput.placeholder = 'Paste relevant cURL command, JSON request body, or server stack trace…'; - } -} - -function setQuickDept(dept) { - const el = document.getElementById('createDepartment'); - if (el) { - el.value = dept; - el.focus(); - } -} - -function openCreateModal(defaultType) { - setCreateTicketType(defaultType === 'general' ? 'general' : 'application'); - document.getElementById('modalCreate').classList.add('active'); - createFormLinks = []; - createFormFiles = []; - renderCreateLinks(); - renderCreateFiles(); -} - -function closeCreateModal() { - document.getElementById('modalCreate').classList.remove('active'); - document.getElementById('modalCreate').querySelector('form').reset(); - createFormLinks = []; - createFormFiles = []; - renderCreateLinks(); - renderCreateFiles(); - setCreateTicketType('application'); -} - -function addCreateLink() { - const input = document.getElementById('createFormLinkInput'); - const url = input.value.trim(); - if (!url) return; - createFormLinks.push({ url }); - input.value = ''; - renderCreateLinks(); -} -function renderCreateLinks() { - const el = document.getElementById('createFormLinks'); - if (!el) return; - el.innerHTML = createFormLinks.length === 0 - ? '
No links added
' - : createFormLinks.map((l, i) => ``).join(''); -} -function removeCreateLink(idx) { createFormLinks.splice(idx, 1); renderCreateLinks(); } -function onCreateFileSelected(e) { - const files = Array.from(e.target.files || []); - if (!files.length) return; - for (const f of files) { - createFormFiles.push({ - name: f.name, - size: f.size, - is_image: f.type.startsWith('image/'), - url: f.type.startsWith('image/') ? URL.createObjectURL(f) : null - }); - } - renderCreateFiles(); - showToast(`${createFormFiles.length} file(s) staged`, 'info'); -} -function renderCreateFiles() { - const el = document.getElementById('createSelectedFiles'); - if (!el) return; - if (createFormFiles.length === 0) { - el.innerHTML = ''; - return; - } - el.innerHTML = createFormFiles.map((f, i) => ` -
- - ${escapeHtml(f.name)} - (${(f.size/1024).toFixed(0)} KB) - -
- `).join(''); -} -function removeCreateFile(idx) { - createFormFiles.splice(idx, 1); - renderCreateFiles(); -} - -async function handleCreateSubmit(e) { - e.preventDefault(); - const btn = e.target.querySelector('button[type="submit"]'); - setLoading(btn, true); - - const isGen = (createTicketType === 'general'); - let payload = {}; - - if (isGen) { - payload = { - ticket_type: 'general', - general_category: document.getElementById('createGeneralCategory')?.value || '', - department: document.getElementById('createDepartment')?.value.trim() || '', - assignee_username: document.getElementById('createAssignee').value, - title: document.getElementById('createTitle').value.trim(), - app: 'General / Non-App', - feature: document.getElementById('createGeneralCategory')?.value || 'General', - priority: document.querySelector('input[name="createPriority"]:checked')?.value || 'P1', - description: document.getElementById('createDescription').value.trim(), - assistance: document.getElementById('createAssistance').value.trim(), - context: document.getElementById('createContext').value, - links: createFormLinks.map(l => l.url || l), - files: createFormFiles.map(l => l.url || l), - files: createFormFiles - }; - if (!payload.assignee_username || !payload.title || !payload.general_category || !payload.department || !payload.description || !payload.assistance) { - showToast('Fill all required general ticket fields', 'error'); - setLoading(btn, false); - return; - } - } else { - payload = { - ticket_type: 'application', - assignee_username: document.getElementById('createAssignee').value, - title: document.getElementById('createTitle').value.trim(), - app: document.getElementById('createApp').value, - version: document.getElementById('createVersion').value.trim(), - feature: document.getElementById('createFeature').value.trim(), - api_key: document.getElementById('createApiKey').value.trim(), - issue_type: document.getElementById('createIssueType').value, - priority: document.querySelector('input[name="createPriority"]:checked')?.value || 'P1', - description: document.getElementById('createDescription').value.trim(), - assistance: document.getElementById('createAssistance').value.trim(), - context: document.getElementById('createContext').value, - links: createFormLinks - }; - if (!payload.assignee_username || !payload.title || !payload.app || !payload.version || !payload.feature || !payload.issue_type || !payload.description || !payload.assistance) { - showToast('Fill all required fields', 'error'); - setLoading(btn, false); - return; - } - } - - try { - const data = await khiraSend('/khira/api/tickets', { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(payload) - }); - if (data.ticket) { - closeCreateModal(); - showToast(`Ticket ${data.ticket.id} created`, 'success'); - await refreshData(); - switchSection('tickets'); - openDrawer(data.ticket.id); - } else { - showToast(data.error || 'Failed to create', 'error'); - } - } catch (err) { - showToast('Failed to create ticket', 'error'); - } finally { - setLoading(btn, false); - } -} - -function openHoldModal() { if (!activeTicketId) return; holdTargetTicketId = activeTicketId; document.getElementById('modalHold').classList.add('active'); } -function closeHoldModal() { document.getElementById('modalHold').classList.remove('active'); document.getElementById('holdReason').value = ''; holdTargetTicketId = null; } -async function handleHoldSubmit(e) { - e.preventDefault(); - const reason = document.getElementById('holdReason').value.trim(); - if (!reason || !holdTargetTicketId) return; - try { - await khiraSend(`/khira/api/tickets/${encodeURIComponent(holdTargetTicketId)}/hold`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ reason }) - }); - closeHoldModal(); - showToast('Ticket placed on hold', 'success'); - await refreshData(); - openDrawer(holdTargetTicketId); - } catch (err) { showToast('Failed to put on hold', 'error'); } -} - -function openCompleteModal() { if (!activeTicketId) return; completeTargetTicketId = activeTicketId; document.getElementById('modalComplete').classList.add('active'); } -function closeCompleteModal() { document.getElementById('modalComplete').classList.remove('active'); document.getElementById('completeResolution').value = ''; completeTargetTicketId = null; } -async function handleCompleteSubmit(e) { - e.preventDefault(); - const resolution = document.getElementById('completeResolution').value.trim(); - if (!resolution || !completeTargetTicketId) return; - try { - await khiraSend(`/khira/api/tickets/${encodeURIComponent(completeTargetTicketId)}/complete`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ resolution }) - }); - closeCompleteModal(); - showToast('Ticket marked completed', 'success'); - await refreshData(); - openDrawer(completeTargetTicketId); - } catch (err) { showToast('Failed to complete', 'error'); } -} - -function openReportErrorModal() { document.getElementById('modalReportError').classList.add('active'); } -function closeReportErrorModal() { document.getElementById('modalReportError').classList.remove('active'); document.getElementById('modalReportError').querySelector('form').reset(); } -async function handleReportErrorSubmit(e) { - e.preventDefault(); - const payload = { - app: document.getElementById('errFormApp').value, - environment: document.getElementById('errFormEnv').value, - service: document.getElementById('errFormService').value.trim(), - endpoint: document.getElementById('errFormEndpoint').value.trim(), - exception_type: document.getElementById('errFormException').value.trim(), - severity: document.querySelector('input[name="errFormSeverity"]:checked')?.value || 'MEDIUM', - message: document.getElementById('errFormMessage').value.trim(), - stack_trace: document.getElementById('errFormTrace').value, - payload: document.getElementById('errFormPayload').value - }; - if (!payload.app || !payload.service || !payload.exception_type || !payload.message) { showToast('Fill all required fields', 'error'); return; } - try { - const data = await khiraSend('/khira/api/errors', { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(payload) - }); - if (data.error) { - closeReportErrorModal(); - showToast(`Error ${data.error.id} ingested`, 'success'); - await refreshData(); - switchSection('errors'); - } else { - showToast('Failed to ingest', 'error'); - } - } catch (err) { - showToast('Failed to ingest error', 'error'); - } -} - -function openEscalateModal(errorId) { - const e = allErrors.find(x => x.id === errorId); - if (!e) return; - currentEscalateErrorId = errorId; - document.getElementById('escalateErrId').textContent = e.id; - const sevEl = document.getElementById('escalateErrSev'); - sevEl.textContent = e.severity; - sevEl.className = 'esc-sev'; - document.getElementById('escalateErrType').textContent = e.exception_type; - document.getElementById('escalateErrMsg').textContent = e.message; - document.getElementById('escalateTitle').value = `${e.exception_type}: ${e.message.slice(0, 60)}`; - document.getElementById('modalEscalate').classList.add('active'); -} -function closeEscalateModal() { document.getElementById('modalEscalate').classList.remove('active'); currentEscalateErrorId = null; } -async function handleEscalateSubmit(e) { - e.preventDefault(); - if (!currentEscalateErrorId) return; - const title = document.getElementById('escalateTitle').value.trim(); - const assignee = document.getElementById('escalateAssignee').value; - const priority = document.querySelector('input[name="escalatePriority"]:checked')?.value || 'P0'; - const notes = document.getElementById('escalateNotes').value.trim(); - if (!title || !assignee) { showToast('Title and assignee required', 'error'); return; } - try { - const data = await khiraSend(`/khira/api/errors/${encodeURIComponent(currentEscalateErrorId)}/escalate`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ title, assignee_username: assignee, priority, notes }) - }); - if (data.ticket) { - closeEscalateModal(); - showToast(`Escalated to ${data.ticket.id}`, 'success'); - await refreshData(); - switchSection('tickets'); - openDrawer(data.ticket.id); - } else { - showToast('Failed to escalate', 'error'); - } - } catch (err) { showToast('Failed to escalate', 'error'); } -} - -function openResolveErrorModal(errorId) { resolveTargetErrorId = errorId; document.getElementById('modalResolveError').classList.add('active'); } -function closeResolveErrorModal() { document.getElementById('modalResolveError').classList.remove('active'); document.getElementById('resolveErrorNotes').value = ''; resolveTargetErrorId = null; } -async function handleResolveErrorSubmit(e) { - e.preventDefault(); - const notes = document.getElementById('resolveErrorNotes').value.trim(); - if (!notes || !resolveTargetErrorId) return; - try { - await khiraSend(`/khira/api/errors/${encodeURIComponent(resolveTargetErrorId)}/status`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ status: 'resolved', resolution_notes: notes }) - }); - closeResolveErrorModal(); - showToast('Error marked resolved', 'success'); - await refreshData(); - } catch (err) { showToast('Failed to resolve', 'error'); } -} - -function openProfileModal() { - if (!currentUser) return; - document.getElementById('profAvatar').textContent = currentUser.avatar || '👤'; - document.getElementById('profName').textContent = currentUser.name; - document.getElementById('profUsername').textContent = '@' + currentUser.username; - document.getElementById('profRole').textContent = currentUser.role_display; - document.getElementById('profInputName').value = currentUser.name; - document.getElementById('profInputRole').value = currentUser.role; - document.querySelectorAll('input[name="profAvatarRadio"]').forEach(r => { r.checked = r.value === currentUser.avatar; }); - document.getElementById('profInputPassword').value = ''; - document.getElementById('modalProfile').classList.add('active'); -} -function closeProfileModal() { document.getElementById('modalProfile').classList.remove('active'); } -async function handleProfileSubmit(e) { - e.preventDefault(); - const name = document.getElementById('profInputName').value.trim(); - const role = document.getElementById('profInputRole').value; - const avatar = document.querySelector('input[name="profAvatarRadio"]:checked')?.value || currentUser.avatar; - const password = document.getElementById('profInputPassword').value; - try { - const data = await khiraSend('/khira/api/auth/profile', { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name, role, avatar, password: password || undefined }) - }); - if (data.user) { - currentUser = data.user; - localStorage.setItem('khira_active_user', currentUser.username); - updateUserUI(); - closeProfileModal(); - showToast('Profile updated', 'success'); - await loadTeamUsers(); - } else { - showToast(data.error || 'Failed to update', 'error'); - } - } catch (err) { showToast('Failed to update profile', 'error'); } -} - -function openLinkModal() { - document.getElementById('modalLink').classList.add('active'); - setTimeout(() => document.getElementById('linkUrlInput').focus(), 200); -} -function closeLinkModal() { - document.getElementById('modalLink').classList.remove('active'); - document.getElementById('linkUrlInput').value = ''; -} -function handleLinkSubmit(e) { - e.preventDefault(); - const url = document.getElementById('linkUrlInput').value.trim(); - if (!url) return; - linkComposerAttach = { url }; - const ta = document.getElementById('remarkText'); - if (ta) { - const cur = ta.value; - ta.value = (cur ? cur + ' ' : '') + url; - ta.focus(); - ta.setSelectionRange(ta.value.length, ta.value.length); - } - closeLinkModal(); - showToast('Link attached', 'info'); -} - -/* ════════════════════════════════════════════════════════════════════ - NOTIFICATIONS - ════════════════════════════════════════════════════════════════════ */ -function toggleNotifDropdown() { document.getElementById('notifDropdown').classList.toggle('active'); } -async function refreshNotifications() { - if (!currentUser) return; - try { - const data = await khiraFetch('/khira/api/notifications', { headers: { 'X-Khira-User': currentUser.username } }); - notificationsList = data.notifications || []; - renderNotifications(); - const unread = notificationsList.filter(n => !n.read).length; - document.getElementById('notifDot').classList.toggle('active', unread > 0); - if (unread > lastUnreadCount && lastUnreadCount !== 0 && desktopAlertsEnabled) { - fireDesktopNotification(notificationsList[0]); - } - lastUnreadCount = unread; - } catch (err) { console.error(err); } -} -function renderNotifications() { - const el = document.getElementById('notifList'); - if (!notificationsList.length) { el.innerHTML = '
No notifications yet
'; return; } - el.innerHTML = notificationsList.slice(0, 12).map(n => `
${escapeHtml(n.title || 'Notification')}
${formatTime(n.created_at || n.time)}
`).join(''); -} -function onNotifClick(id) { - const n = notificationsList.find(x => x.id === id); - if (n && n.ticket_id) openDrawer(n.ticket_id); - document.getElementById('notifDropdown').classList.remove('active'); -} -async function markAllRead() { - try { - await khiraSend('/khira/api/notifications/read', { method: 'POST', headers: { 'X-Khira-User': currentUser.username } }); - await refreshNotifications(); - showToast('All marked read', 'info'); - } catch (err) { showToast('Failed', 'error'); } -} - -/* ════════════════════════════════════════════════════════════════════ - ERRORS VIEW - ════════════════════════════════════════════════════════════════════ */ -async function loadErrors(silent = false) { - try { - const headers = { 'X-Khira-User': currentUser.username }; - const [errsRes, statsRes] = await Promise.all([ - khiraFetch('/khira/api/errors', { headers }), - khiraFetch('/khira/api/errors/stats', { headers }) - ]); - allErrors = errsRes.errors || []; - errorStats = statsRes; - updateErrorStatsUI(); - } catch (err) { if (!silent) console.error(err); } -} -function updateErrorStatsUI() { - tickNumber(document.getElementById('errTotal'), errorStats.total || 0); - tickNumber(document.getElementById('errUnresolved'), errorStats.unresolved || 0); - tickNumber(document.getElementById('errEscalated'), errorStats.escalated || 0); - tickNumber(document.getElementById('errResolved'), errorStats.resolved || 0); - setText('navCountErrors', errorStats.unresolved || allErrors.length || 0); -} -function onErrSearchInput(v) { errSearchQuery = v.toLowerCase(); renderErrors(); } -function onErrFilterChange(type, val) { - if (type === 'app') errFilterApp = val; - if (type === 'severity') errFilterSeverity = val; - if (type === 'status') errFilterStatus = val; - renderErrors(); -} -function switchErrView(view) { - currentErrView = view; - document.querySelectorAll('#viewErrors .view-switch-btn').forEach(b => b.classList.toggle('active', b.dataset.view === view)); - document.getElementById('errTableView').hidden = view !== 'table'; - document.getElementById('errCardsView').hidden = view !== 'cards'; - renderErrors(); -} -function getFilteredErrors() { - return allErrors.filter(e => { - if (errFilterApp && e.app !== errFilterApp) return false; - if (errFilterSeverity && e.severity !== errFilterSeverity) return false; - if (errFilterStatus && e.status !== errFilterStatus) return false; - if (errSearchQuery) { - const hay = `${e.id} ${e.exception_type} ${e.message} ${e.endpoint} ${e.app}`.toLowerCase(); - if (!hay.includes(errSearchQuery)) return false; - } - return true; - }); -} -function renderErrors() { - const filtered = getFilteredErrors(); - if (currentErrView === 'table') renderErrorsTable(filtered); - else renderErrorsCards(filtered); -} -function renderErrorsTable(filtered) { - const tbody = document.getElementById('errorsTbody'); - const empty = document.getElementById('errorsEmpty'); - if (!filtered.length) { tbody.innerHTML = ''; empty.hidden = false; return; } - empty.hidden = true; - tbody.innerHTML = filtered.map(e => { - const sev = (e.severity || 'MEDIUM').toUpperCase(); - const sevCls = sev.toLowerCase(); - const sLabel = e.status === 'resolved' ? 'Resolved' : (e.escalated_ticket_id ? 'Escalated' : 'Unresolved'); - const sCls = e.status === 'resolved' ? 'resolved' : (e.escalated_ticket_id ? 'escalated' : 'unresolved'); - return ` - ${escapeHtml(e.id)} - ${escapeHtml(sev)} - ${escapeHtml(sLabel)} - ${escapeHtml(e.exception_type)} - ${escapeHtml(e.message)} - ${escapeHtml(e.app || '—')} - ${escapeHtml(e.endpoint || '—')} - ${formatTime(e.last_seen)} - ${e.events || 1} -
- ${e.status !== 'resolved' ? `` : ''} - ${e.status === 'unresolved' ? `` : ''} -
- `; - }).join(''); - tbody.querySelectorAll('tr').forEach(row => { - row.addEventListener('click', () => { - const e = allErrors.find(x => x.id === row.dataset.id); - if (e && e.status === 'unresolved') openEscalateModal(e.id); - }); - }); -} -function renderErrorsCards(filtered) { - const grid = document.getElementById('errCardsView'); - if (!filtered.length) { grid.innerHTML = '
No errors tracked.
'; return; } - grid.innerHTML = filtered.map((e, i) => { - const sev = (e.severity || 'MEDIUM').toUpperCase(); - const sevColor = { CRITICAL: '#EF4444', HIGH: '#F59E0B', MEDIUM: '#06B6D4', LOW: '#64748B' }[sev] || '#06B6D4'; - const sLabel = e.status === 'resolved' ? 'Resolved' : (e.escalated_ticket_id ? 'Escalated' : 'Unresolved'); - const sCls = e.status === 'resolved' ? 'resolved' : (e.escalated_ticket_id ? 'escalated' : 'unresolved'); - return `
-
- ${escapeHtml(e.id)} -
- ${escapeHtml(sev)} - ${escapeHtml(sLabel)} -
-
-
${escapeHtml(e.exception_type)}
-
${escapeHtml(e.message)}
-
- ${escapeHtml(e.app || '—')} · ${escapeHtml(e.endpoint || '—')} - ${e.events || 1} -
-
`; - }).join(''); - grid.querySelectorAll('.err-card').forEach(card => { - card.addEventListener('click', () => { - const e = allErrors.find(x => x.id === card.dataset.id); - if (e && e.status === 'unresolved') openEscalateModal(e.id); - }); - }); -} - -/* ════════════════════════════════════════════════════════════════════ - DESKTOP ALERTS - ════════════════════════════════════════════════════════════════════ */ -function initAlertsToggle() { - desktopAlertsEnabled = (localStorage.getItem('khira_alerts') === 'enabled') && (Notification && Notification.permission === 'granted'); - const t = document.getElementById('alertsToggle'); - if (t) t.checked = desktopAlertsEnabled; -} -function toggleAlerts(on) { - if (on) { - if (!('Notification' in window)) { showToast('Notifications unsupported', 'error'); document.getElementById('alertsToggle').checked = false; return; } - if (Notification.permission === 'granted') { - desktopAlertsEnabled = true; localStorage.setItem('khira_alerts', 'enabled'); showToast('Alerts enabled', 'success'); - } else if (Notification.permission !== 'denied') { - Notification.requestPermission().then(p => { - if (p === 'granted') { desktopAlertsEnabled = true; localStorage.setItem('khira_alerts', 'enabled'); showToast('Alerts enabled', 'success'); } - else { showToast('Permission denied', 'error'); document.getElementById('alertsToggle').checked = false; } - }); - } else { showToast('Permission blocked in browser', 'error'); document.getElementById('alertsToggle').checked = false; } - } else { - desktopAlertsEnabled = false; localStorage.setItem('khira_alerts', 'disabled'); showToast('Alerts disabled', 'info'); - } -} -function fireDesktopNotification(n) { - if (!desktopAlertsEnabled || !n) return; - try { new Notification('Khira · ' + (n.title || 'New notification'), { body: n.body || '' }); } catch (e) {} -} - -/* ════════════════════════════════════════════════════════════════════ - TOASTS - ════════════════════════════════════════════════════════════════════ */ -function showToast(message, type = 'info') { - const stack = document.getElementById('toastStack'); - if (!stack) return; - const icons = { success: 'circle-check', error: 'circle-exclamation', info: 'circle-info' }; - const t = document.createElement('div'); - t.className = `toast ${type}`; - t.innerHTML = `
${escapeHtml(message)}
`; - stack.appendChild(t); - setTimeout(() => { t.classList.add('removing'); setTimeout(() => t.remove(), 200); }, 3500); -} - -/* ════════════════════════════════════════════════════════════════════ - HELPERS - ════════════════════════════════════════════════════════════════════ */ -function setLoading(btn, on) { - if (!btn) return; - if (on) { - btn.classList.add('is-loading'); - btn.dataset._orig = btn.innerHTML; - btn.innerHTML = ''; - btn.disabled = true; - } else { - btn.classList.remove('is-loading'); - if (btn.dataset._orig) { btn.innerHTML = btn.dataset._orig; delete btn.dataset._orig; } - btn.disabled = false; - } -} -function closeEverything() { - closeDrawer(); - document.querySelectorAll('.modal-overlay.active').forEach(m => m.classList.remove('active')); - document.getElementById('notifDropdown').classList.remove('active'); - closeMobileSidebar(); -} -function escapeHtml(s) { - if (s == null) return ''; - return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); -} -function formatTime(iso) { - if (!iso) return '—'; - const d = new Date(iso); - if (isNaN(d.getTime())) return iso; - const diff = Date.now() - d.getTime(); - const sec = Math.floor(diff / 1000); - if (sec < 60) return 'just now'; - const min = Math.floor(sec / 60); - if (min < 60) return `${min}m ago`; - const hr = Math.floor(min / 60); - if (hr < 24) return `${hr}h ago`; - const days = Math.floor(hr / 24); - if (days < 30) return `${days}d ago`; - return d.toLocaleDateString(); -} - -/* Spin keyframes injected at runtime to avoid CSS conflicts */ -const _style = document.createElement('style'); -_style.textContent = `@keyframes spin { to { transform: rotate(360deg); } }`; -document.head.appendChild(_style); - -/* ════════════════════════════════════════════════════════════════════ - GLOBAL HANDLERS EXPOSURE (for inline onclick) - ════════════════════════════════════════════════════════════════════ */ -window.toggleTheme = toggleTheme; -window.switchAuthTab = switchAuthTab; -window.handleLoginSubmit = handleLoginSubmit; -window.handleRegisterSubmit = handleRegisterSubmit; -window.quickLoginAs = quickLoginAs; -window.handleLogout = handleLogout; -window.openProfileModal = openProfileModal; -window.closeProfileModal = closeProfileModal; -window.handleProfileSubmit = handleProfileSubmit; -window.openCreateModal = openCreateModal; -window.closeCreateModal = closeCreateModal; -window.setCreateTicketType = setCreateTicketType; -window.setQuickDept = setQuickDept; -window.handleCreateSubmit = handleCreateSubmit; -window.addCreateLink = addCreateLink; -window.removeCreateLink = removeCreateLink; -window.onCreateFileSelected = onCreateFileSelected; -window.openHoldModal = openHoldModal; -window.closeHoldModal = closeHoldModal; -window.handleHoldSubmit = handleHoldSubmit; -window.openCompleteModal = openCompleteModal; -window.closeCompleteModal = closeCompleteModal; -window.handleCompleteSubmit = handleCompleteSubmit; -window.openReportErrorModal = openReportErrorModal; -window.closeReportErrorModal = closeReportErrorModal; -window.handleReportErrorSubmit = handleReportErrorSubmit; -window.openEscalateModal = openEscalateModal; -window.closeEscalateModal = closeEscalateModal; -window.handleEscalateSubmit = handleEscalateSubmit; -window.openResolveErrorModal = openResolveErrorModal; -window.closeResolveErrorModal = closeResolveErrorModal; -window.handleResolveErrorSubmit = handleResolveErrorSubmit; -window.openLinkModal = openLinkModal; -window.closeLinkModal = closeLinkModal; -window.handleLinkSubmit = handleLinkSubmit; -window.openDrawer = openDrawer; -window.closeDrawer = closeDrawer; -window.submitRemark = submitRemark; -window.reassignTicket = reassignTicket; -window.changePriority = changePriority; -window.resumeTicket = resumeTicket; -window.copyText = copyText; -window.removeDrawerLink = removeDrawerLink; -window.removeDrawerFile = removeDrawerFile; -window.onDrawerFileSelected = onDrawerFileSelected; -window.switchSection = switchSection; -window.switchScope = switchScope; -window.switchView = switchView; -window.onSearchInput = onSearchInput; -window.onFilterChange = onFilterChange; -window.focusSearch = focusSearch; -window.onErrSearchInput = onErrSearchInput; -window.onErrFilterChange = onErrFilterChange; -window.switchErrView = switchErrView; -window.toggleNotifDropdown = toggleNotifDropdown; -window.markAllRead = markAllRead; -window.onNotifClick = onNotifClick; -window.toggleAlerts = toggleAlerts; -window.openMobileSidebar = openMobileSidebar; -window.closeMobileSidebar = closeMobileSidebar; -window.filterBySidebarWorkload = filterBySidebarWorkload; -window.removeCreateFile = removeCreateFile; \ No newline at end of file +document.addEventListener('change',e=>{ + const T=e.target,a=T.dataset?.act; + if(a==='assign'&&T.value)act('reassign',{assignee_username:T.value},'Ticket reassigned'); + if(a==='prio')act('priority',{priority:T.value},'Priority updated'); + if(T.id==='fp'){S.pr=T.value;render(true)} + if(T.id==='ft'){S.ty=T.value;render(true)} +}); +document.addEventListener('input',e=>{ + e.target.closest('.fld')?.classList.remove('bad'); + if(e.target.id==='q'){S.q=e.target.value.toLowerCase();render(false)} + if(e.target.id==='rt'){e.target.style.height='auto';e.target.style.height=e.target.scrollHeight+'px'} +}); +document.addEventListener('submit',e=>{if(e.target.id==='rf'){e.preventDefault();remark()}}); +document.addEventListener('keydown',e=>{ + if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='k'){e.preventDefault();$('#q').focus();$('#q').select()} + if((e.metaKey||e.ctrlKey)&&e.key==='Enter'&&e.target.id==='rt'){e.preventDefault();remark()} + if(e.key==='Enter'&&e.target.matches?.('[role=button]'))e.target.click(); +}); +$('#fIn').onsubmit=async e=>{ + e.preventDefault();if(!chk(e.target))return; + await busy(e.target.querySelector('.fb'),async()=>{ + const r=await api('/khira/api/auth/login','POST',{username:$('#lu').value.trim(),password:$('#lp').value}); + if(r.user){toast(`Signed in as ${r.user.name}`);enter(r.user)}else toast(r.error||'Invalid credentials','err'); + }); +}; +$('#fUp').onsubmit=async e=>{ + e.preventDefault();if(!chk(e.target))return; + await busy(e.target.querySelector('.fb'),async()=>{ + const r=await api('/khira/api/auth/register','POST',{name:$('#rn').value.trim(),username:$('#ru').value.trim(),role:$('#rr').value,password:$('#rp').value}); + if(r.user){toast(`Welcome, ${r.user.name}`);enter(r.user)}else toast(r.error||'Registration failed','err'); + }); +}; +setInterval(()=>{if(S.u&&!document.hidden)refresh()},8000); +document.addEventListener('DOMContentLoaded',boot); diff --git a/web/khira/index.html b/web/khira/index.html index 22f3647..bc9a57f 100644 --- a/web/khira/index.html +++ b/web/khira/index.html @@ -1,1253 +1,92 @@ - + - - - - Khira — Aurora Engineering Console - - - - - - + + + +Khira + + + + + + + - - +
+
+ +

Khira

+

Tickets and error tracking for your engineering team.

+
+
+ + + +
+ +
Demo accounts
+
+
- - - +