Files
Unified_Dashboard_Suite_Go/web/khira/app.js
T

1918 lines
105 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════════════════
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
═══════════════════════════════════════════════════════════════════════════ */
'use strict';
/* ════════════════════════════════════════════════════════════════════
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' }
];
}
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' }
];
}
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 };
}
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);
}
}
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);
}
}
/* ════════════════════════════════════════════════════════════════════
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);
}
/* ─── 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();
}
/* ─── 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;
});
});
}
/* ─── 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 = '';
});
});
}
/* ─── 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);
});
}
/* ─── 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);
});
/* ════════════════════════════════════════════════════════════════════
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 = `<i class="fa-solid fa-code"></i> ${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 => `<option value="${u.username}">${u.avatar || '👤'} ${escapeHtml(u.name)} · ${escapeHtml(u.role_display)}</option>`).join('');
const c = document.getElementById('createAssignee');
const d = document.getElementById('drawerAssigneeSelect');
const e = document.getElementById('escalateAssignee');
if (c) c.innerHTML = '<option value="">Choose developer…</option>' + opts;
if (d) d.innerHTML = '<option value="">Reassign…</option>' + opts;
if (e) e.innerHTML = '<option value="">Choose developer…</option>' + 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 = '<div class="kanban-empty">No tickets</div>';
} 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
? `<span class="type-pill type-pill-general"><i class="fa-solid fa-gear"></i> General</span>`
: `<span class="type-pill type-pill-app"><i class="fa-solid fa-rocket"></i> App</span>`;
const categoryOrApp = isGen
? `<span class="kc-app general-app" title="${escapeHtml(t.department ? t.general_category + ' · ' + t.department : t.general_category || 'General')}"><i class="fa-solid fa-layer-group"></i> ${escapeHtml(t.general_category || t.department || 'General')}</span>`
: `<span class="kc-app" title="${escapeHtml(t.app || t.app_name || '—')}"><i class="fa-solid fa-cube"></i> ${escapeHtml(t.app || t.app_name || '—')}</span>`;
const assignee = t.assignee ? (t.assignee.avatar || '👤') : (t.assigned_to_role === 'Frontend Dev' ? '🎨' : t.assigned_to_role === 'Tester' ? '🕵️‍♂️' : '👨‍💻');
const remarksCount = (t.remarks || []).length;
return `<div class="kanban-card tilt" data-id="${t.id}" style="--card-accent: ${accentColor}" tabindex="0" role="button">
<div class="kc-head">
<div style="display:flex;align-items:center;gap:6px;">
<span class="kc-id">${escapeHtml(t.id)}</span>
${typeTag}
</div>
<span class="kc-pri ${priClass}">${escapeHtml(pri)}</span>
</div>
<div class="kc-title">${escapeHtml(t.title)}</div>
<div class="kc-meta">
${categoryOrApp}
<div class="kc-right">
${remarksCount > 0 ? `<span class="kc-remarks"><i class="fa-regular fa-comment"></i> ${remarksCount}</span>` : ''}
<span class="kc-assignee" title="${escapeHtml(t.assignee ? t.assignee.name : (t.assigned_to_name || ''))}">${assignee}</span>
</div>
</div>
</div>`;
}
/* ════════════════════════════════════════════════════════════════════
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
? `<span class="type-pill type-pill-general"><i class="fa-solid fa-gear"></i> General</span>`
: `<span class="type-pill type-pill-app"><i class="fa-solid fa-rocket"></i> App</span>`;
const appCol = isGen
? `<span class="tt-app tt-app-general" title="${escapeHtml(t.department || t.general_category || '')}"><i class="fa-solid fa-layer-group"></i> ${escapeHtml(t.general_category || t.department || 'General')}</span>`
: `<span class="tt-app"><i class="fa-solid fa-cube"></i> ${escapeHtml(t.app || t.app_name || '—')}</span>`;
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 `<tr data-id="${t.id}">
<td class="tt-id">${escapeHtml(t.id)}</td>
<td>${typePill}</td>
<td class="tt-title" title="${escapeHtml(t.title)}">${escapeHtml(t.title)}</td>
<td>${appCol}</td>
<td><span class="kc-pri ${pri.toLowerCase()}">${escapeHtml(pri)}</span></td>
<td><div class="tt-assignee"><span class="tt-assignee-avatar">${assigneeAvatar}</span>${escapeHtml(assigneeName)}</div></td>
<td><div class="tt-assignee"><span class="tt-assignee-avatar">${reporterAvatar}</span>${escapeHtml(reporterName)}</div></td>
<td><span class="tt-status ${s}">${sLabel}</span></td>
<td class="tt-time">${formatTime(t.updated_at)}</td>
<td><div class="tt-actions"><button class="tt-action" onclick="event.stopPropagation(); openDrawer('${t.id}')" title="Open"><i class="fa-solid fa-arrow-right"></i></button></div></td>
</tr>`;
}).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 `<div class="ds-link-item"><i class="fa-solid fa-link" style="color: var(--aurora-2); font-size: 10px;"></i><a href="${escapeHtml(url)}" target="_blank" rel="noopener">${escapeHtml(url.replace(/^https?:\/\//, '').slice(0, 60))}</a><button class="ds-link-rm" onclick="removeDrawerLink(${i})"><i class="fa-solid fa-xmark"></i></button></div>`;
}).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) => `<div class="ds-file"><div class="ds-file-thumb">${f.is_image || f.type === 'image' ? `<img src="${escapeHtml(f.url)}" alt="">` : `<i class="fa-solid fa-file"></i>`}</div><div class="ds-file-name">${escapeHtml(f.name || 'file')}</div><div class="ds-file-meta"><span>${escapeHtml((f.size || 0) + ' B')}</span><button class="ds-link-rm" onclick="removeDrawerFile(${i})"><i class="fa-solid fa-xmark"></i></button></div></div>`).join('');
} else {
filesEl.innerHTML = '';
}
const tl = document.getElementById('drawerTimeline');
const remarks = t.remarks || [];
setText('drawerRemarksCount', remarks.length);
if (!remarks.length) {
tl.innerHTML = '<div style="font-size: 11px; color: var(--fg-3); padding: 8px;">No remarks yet — be the first to post.</div>';
} 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 `<div class="tl-entry system"><div class="tl-head"><span class="tl-author"><i class="fa-solid fa-bolt"></i> Khira System</span><span class="tl-time">${formatTime(r.created_at)}</span></div><div class="tl-body">${escapeHtml(rText)}</div></div>`;
}
return `<div class="tl-entry"><div class="tl-head"><span class="tl-author">${rAuthor}</span><span class="tl-time">${formatTime(r.created_at)}</span></div><div class="tl-body">${escapeHtml(rText)}${(r.links && r.links.length) ? r.links.map(l => `<a class="tl-link" href="${escapeHtml(l.url || l)}" target="_blank"><i class="fa-solid fa-link"></i> ${escapeHtml((l.url || l).replace(/^https?:\/\//, '').slice(0, 30))}</a>`).join('') : ''}</div></div>`;
}).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 = '<i class="fa-solid fa-layer-group"></i> 2. Domain &amp; 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 <span class="req">*</span>';
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 = '<i class="fa-solid fa-cubes"></i> 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 <span class="req">*</span>';
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
? '<div style="font-size: 10px; color: var(--fg-3); padding: 4px 0;">No links added</div>'
: createFormLinks.map((l, i) => `<div class="link-row"><i class="fa-solid fa-link" style="color: var(--aurora-2); font-size: 9px;"></i><a href="${escapeHtml(l.url)}" target="_blank">${escapeHtml(l.url.replace(/^https?:\/\//, '').slice(0, 40))}</a><button type="button" class="ds-link-rm" onclick="removeCreateLink(${i})"><i class="fa-solid fa-xmark"></i></button></div>`).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) => `
<div class="file-chip" style="display:inline-flex; align-items:center; gap:6px; background:var(--bg-elevated); border:1px solid var(--border); border-radius:var(--r-sm); padding:4px 8px; margin:3px; font-size:11px;">
<i class="fa-solid ${f.is_image ? 'fa-image' : 'fa-file'}" style="color:var(--aurora-2)"></i>
<span style="max-width:140px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${escapeHtml(f.name)}</span>
<span style="color:var(--fg-3); font-size:10px;">(${(f.size/1024).toFixed(0)} KB)</span>
<button type="button" onclick="removeCreateFile(${i})" style="background:none; border:none; color:var(--fg-3); cursor:pointer; padding:0 2px;"><i class="fa-solid fa-xmark"></i></button>
</div>
`).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 = '<div class="notif-empty">No notifications yet</div>'; return; }
el.innerHTML = notificationsList.slice(0, 12).map(n => `<div class="notif-item ${n.read ? '' : 'unread'}" onclick="onNotifClick('${n.id || ''}')"><div class="notif-icon"><i class="fa-solid fa-${n.icon || 'bell'}"></i></div><div class="notif-body"><div class="notif-title">${escapeHtml(n.title || 'Notification')}</div><div class="notif-time">${formatTime(n.created_at || n.time)}</div></div></div>`).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 `<tr data-id="${e.id}">
<td class="tt-id">${escapeHtml(e.id)}</td>
<td><span class="kc-pri ${sevCls}">${escapeHtml(sev)}</span></td>
<td><span class="err-card-status ${sCls}">${escapeHtml(sLabel)}</span></td>
<td><code class="mono" style="font-size: 11px; color: var(--fg-0); font-weight: 600;">${escapeHtml(e.exception_type)}</code></td>
<td style="max-width: 280px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${escapeHtml(e.message)}</td>
<td><span class="tt-app">${escapeHtml(e.app || '—')}</span></td>
<td class="tt-id" style="max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${escapeHtml(e.endpoint || '—')}</td>
<td class="tt-time">${formatTime(e.last_seen)}</td>
<td><span class="err-card-events"><i class="fa-solid fa-bolt"></i> ${e.events || 1}</span></td>
<td><div class="tt-actions">
${e.status !== 'resolved' ? `<button class="tt-action" onclick="event.stopPropagation(); openEscalateModal('${e.id}')" title="Escalate"><i class="fa-solid fa-arrow-up-right-from-square"></i></button>` : ''}
${e.status === 'unresolved' ? `<button class="tt-action" onclick="event.stopPropagation(); openResolveErrorModal('${e.id}')" title="Resolve"><i class="fa-solid fa-check"></i></button>` : ''}
</div></td>
</tr>`;
}).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 = '<div style="grid-column: 1/-1; text-align: center; color: var(--fg-3); padding: 48px;">No errors tracked.</div>'; 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 `<div class="err-card tilt" data-id="${e.id}" style="--card-accent: ${sevColor}; animation-delay: ${i * 40}ms">
<div class="err-card-head">
<span class="err-card-id">${escapeHtml(e.id)}</span>
<div style="display:flex; gap:4px; align-items:center;">
<span class="err-card-pri ${sev}">${escapeHtml(sev)}</span>
<span class="err-card-status ${sCls}">${escapeHtml(sLabel)}</span>
</div>
</div>
<div class="err-card-exception">${escapeHtml(e.exception_type)}</div>
<div class="err-card-message">${escapeHtml(e.message)}</div>
<div class="err-card-meta">
<span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${escapeHtml(e.app || '—')} · ${escapeHtml(e.endpoint || '—')}</span>
<span class="err-card-events"><i class="fa-solid fa-bolt"></i> ${e.events || 1}</span>
</div>
</div>`;
}).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 = `<i class="fa-solid fa-${icons[type] || 'circle-info'} toast-icon"></i><div class="toast-body">${escapeHtml(message)}</div><button class="toast-close" onclick="this.parentElement.classList.add('removing'); setTimeout(()=>this.parentElement.remove(), 200)"><i class="fa-solid fa-xmark"></i></button>`;
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 = '<i class="fa-solid fa-spinner" style="animation: spin 800ms linear infinite;"></i>';
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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
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;